- ‘NoneType’ object has no attribute ‘find’
- How to resolve AttributeError: ‘list’ object has no attribute ‘find’ in Python
- What causes the AttributeError: ‘list’ object has no attribute ‘find’?
- How to solve the AttributeError: ‘list’ object has no attribute ‘find’?
- Convert the list to a string using the find() method.
- Search for an element in the list.
- Summary
- У объекта ‘list’ нет атрибута ‘find’
- 3 ответа
- У объекта ‘list’ нет атрибута ‘find’
- 3 ответа
‘NoneType’ object has no attribute ‘find’
Всем привет. Столкнулся с одной неприятной и непонятной проблемой. при попытке вывода кода через принт выдает ошибку
‘NoneType’ object has no attribute ‘find’. я догадываюсь,что не так, но исправить ошибку никак не уддается. надеюсь на вашу помощь
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
import requests from bs4 import BeautifulSoup import csv HOST = 'https://author.today/' URL = 'https://author.today/u/vishnevsky_s_v/works' HEADERS = { 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,' 'application/signed-exchange;v=b3;q=0.9', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)' ' Chrome/89.0.4389.114 Safari/537.36' } def get_html(url, params=''): r = requests.get(url, headers=HEADERS, params=params) return r def get_content(html): soup = BeautifulSoup(html, 'html.parser') items = soup.find_all('div', class_='book-row') # item_img = soup.find_all('div', class_='book-row')#думал попробовать решить проблему через другой поиск cards = [] for item in items: try: cards.append( { 'title': HOST + item.find('div', class_='book-title').get_text(strip=True), 'link_book': HOST + item.find('div', class_='book-title').find('a').get('href'), 'genre': item.find('div', class_='book-genres').get_text(strip=True), 'book_images': HOST + item_img.find('div', class_='cover-image fade-box').find('img').get('src')#здесь ошибка свзяанная с none элементом } ) except: print('xd') return cards def parser(): html = get_html(URL) if html.status_code == 200: print(get_content(html.text)) else: print('Error') parser()
How to resolve AttributeError: ‘list’ object has no attribute ‘find’ in Python
If you are looking for a solution to the error AttributeError: ‘list’ object has no attribute ‘find’, here are the causes of the error and some ways you can use it to fix it. Details are below.
What causes the AttributeError: ‘list’ object has no attribute ‘find’?
The error happens because you call the find() method on the list instead of calling the method on the string.
listInfor = ['visit', 'learnshareit', 'website'] # Call the find() method on the list print(listInfor.find('visit'))
Traceback (most recent call last): File "./prog.py", line 4, in AttributeError: 'list' object has no attribute 'find'
How to solve the AttributeError: ‘list’ object has no attribute ‘find’?
Convert the list to a string using the find() method.
- If you have a list, you want to use the find() method and then convert that list to a string using the join() function.
listInfor = ['visit', 'learnshareit', 'website'] # Convert the list to a string by the join() function newStr = ' '.join(listInfor) print('The string converted to is:', newStr) print(type(newStr)) # Call the find() method on the list print('String to look for at the index:', newStr.find('visit'))
The string converted to is: visit learnshareit website String to look for at the index: 0
Note: The find() method exception will occur if you pass in a string that does not exist. The function will return -1.
listInfor = ['visit', 'learnshareit', 'website'] # Convert the list to a string by the join() function newStr = ' '.join(listInfor) print('The string converted to is:', newStr) print(type(newStr)) # Call the find() method on the list print('String to look for at the index:', newStr.find('World Cup'))
The string converted to is: visit learnshareit website String to look for at the index: -1
As you can see, ‘World Cup’ does not exist in the string, so the function returns -1.
Search for an element in the list.
A convenience of Python is that it has many built-in functions to assist users. Similar to the find() function for searching substrings on strings, the index() function list also has the same function on one’s own.
The list.index() returns the index of the first occurrence of the search value.
- Create a list.
- Use the index() to return the index of the first occurrence of the search element.
listInfor = ['visit', 'learnshareit', 'website'] # Use the list.index() indicates the index of the first occurrence of the search element print('Index of the search element:', listInfor.index('visit'))
Index of the search element: 0
Note: If the search value does not exist, the program will throw a ValueError error.
listInfor = ['visit', 'learnshareit', 'website'] # Use the list.index() indicates the index of the first occurrence of the search element print('Index of the search element:', listInfor.index('Name'))
Traceback (most recent call last): File "./prog.py", line 4, in ValueError: 'Name' is not in list
‘Name’ does not exist in the list, so when using the index() function, the program throws an error ValueError: ‘Name’ is not in list.
Summary
Through this article, you have an idea to fix the AttributeError: ‘list’ object has no attribute ‘find’ in Python. I suggest you use the list.index() function, so you don’t have to convert the list to a string. Leave a comment so I can know how you feel about the article. Thanks for reading!
Maybe you are interested:
My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.
Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java
У объекта ‘list’ нет атрибута ‘find’
Я знаю, что это основной вопрос, но я новичок в python и не могу понять, как его решить. У меня есть список, как в следующем примере:
entities = ["#1= IFCORGANIZATION($,'Autodesk Revit 2014 (ENU)',$,$,$)";, "#5= IFCAPPLICATION(#1,'2014','Autodesk Revit 2014 (ENU)','Revit');"]
Моя проблема заключается в том, как добавить информацию из списка «entities» в словарь в следующем формате:
Я попытался сделать это, используя «find» но я получаю следующую ошибку: ‘list’ object has no attribute ‘find’ , и я не знаю, как это сделать без поиска метода.
3 ответа
Вы можете использовать str.split для обработки строк. Сначала разделите каждую строку элемента с помощью ‘(‘ , с maxsplit, равным 1:
In [48]: dic=dict(e[:-1].split('(', 1) for e in entities) #using [:-1] to filter out ')' . print dic .
затем разделите каждое значение в dict на ‘,’ :
Обратите внимание, что пары ключ-значение в dict не упорядочены, так как вы можете видеть, что ‘#1= IFCORGANIZATION’ не отображается в первую очередь.
zhangxaochen: Большое спасибо за вашу поддержку. Я попробовал ваш код, и он действительно делает то, что мне нужно. Мне не нужно, чтобы словарь был в определенном порядке, так что это не проблема. Спасибо за объяснение тоже. С уважением!
Если вы хотите знать, является ли значение в списке, вы можете использовать in , как это:
>>> my_list = ["one", "two", "three"] >>> "two" in my_list True >>>
Если вам нужно получить позицию значения в списке, вы должны использовать index :
Обратите внимание, что первый элемент списка имеет индекс 0.
Trimax: Спасибо за поддержку. Проблема в том, что данные в списке всегда разные, и поэтому я не могу найти конкретное слово. Мне нужно разделить каждую строку в списке в формате, представленном ранее, чтобы я мог манипулировать информацией и затем использовать ее.
Для поиска шаблонов в строках более полезен модуль Regular Expressions re docs.python.org/3.3/library/re.html, и вы можете извлекать их по группам в списке.
@ Тримакс, ты прав, но понимание списка будет более подходящим. Если вы не знаете, как перебирать список, вы думаете, что все будет в порядке с re?
с помощью re.findall () вы получаете список со всеми соответствиями в строке, и ваш ввод, кажется, имеет шаблон, данные в списке всегда различны, но это не случайное.
@Trimax В моем конкретном случае я не против, если словарь не в правильном порядке. Но если мне так нужно, я воспользуюсь твоим предложением. Спасибо.
>>> import re >>> import ast >>> entities = ["#1= IFCORGANIZATION('$','Autodesk Revit 2014 (ENU)','$','$','$');", "#5= IFCAPPLICATION('#1','2014','Autodesk Revit 2014 (ENU)','Revit');"] >>> entities = [a.strip(';') for a in entities] >>> pattern = re.compile(r'\((.*)\)') >>> dic = <> >>> for a in entities: . s = re.search(pattern, a) . dic[a[:a.index(s.group(0))]] = list(ast.literal_eval(s.group(0))) >>> dic
Это регулярное выражение r’\((.*)\)’ Ищет элементы в ( и ) и преобразует их в список. Это приводит к тому, что подстрока появляется перед скобками в качестве ключа и списка в качестве значения.
Shaktimaan: Спасибо за вашу быструю поддержку. Я не знал этих модулей, поэтому спасибо, что познакомили меня с ними. Мне не удалось заставить ваш код работать, потому что в моей переменной «entity» у меня нет ‘наряду с $, то есть’ $ ‘. Но я думаю, что с некоторыми изменениями все будет хорошо! С уважением.
У объекта ‘list’ нет атрибута ‘find’
Я знаю, что это основной вопрос, но я новичок в python и не могу понять, как его решить. У меня есть список, как в следующем примере:
entities = ["#1= IFCORGANIZATION($,'Autodesk Revit 2014 (ENU)',$,$,$)";, "#5= IFCAPPLICATION(#1,'2014','Autodesk Revit 2014 (ENU)','Revit');"]
Моя проблема заключается в том, как добавить информацию из списка «entities» в словарь в следующем формате:
Я попытался сделать это, используя «find» но я получаю следующую ошибку: ‘list’ object has no attribute ‘find’ , и я не знаю, как это сделать без поиска метода.
3 ответа
Вы можете использовать str.split для обработки строк. Сначала разделите каждую строку элемента с помощью ‘(‘ , с maxsplit, равным 1:
In [48]: dic=dict(e[:-1].split('(', 1) for e in entities) #using [:-1] to filter out ')' . print dic .
затем разделите каждое значение в dict на ‘,’ :
Обратите внимание, что пары ключ-значение в dict не упорядочены, так как вы можете видеть, что ‘#1= IFCORGANIZATION’ не отображается в первую очередь.
zhangxaochen: Большое спасибо за вашу поддержку. Я попробовал ваш код, и он действительно делает то, что мне нужно. Мне не нужно, чтобы словарь был в определенном порядке, так что это не проблема. Спасибо за объяснение тоже. С уважением!
Если вы хотите знать, является ли значение в списке, вы можете использовать in , как это:
>>> my_list = ["one", "two", "three"] >>> "two" in my_list True >>>
Если вам нужно получить позицию значения в списке, вы должны использовать index :
Обратите внимание, что первый элемент списка имеет индекс 0.
Trimax: Спасибо за поддержку. Проблема в том, что данные в списке всегда разные, и поэтому я не могу найти конкретное слово. Мне нужно разделить каждую строку в списке в формате, представленном ранее, чтобы я мог манипулировать информацией и затем использовать ее.
Для поиска шаблонов в строках более полезен модуль Regular Expressions re docs.python.org/3.3/library/re.html, и вы можете извлекать их по группам в списке.
@ Тримакс, ты прав, но понимание списка будет более подходящим. Если вы не знаете, как перебирать список, вы думаете, что все будет в порядке с re?
с помощью re.findall () вы получаете список со всеми соответствиями в строке, и ваш ввод, кажется, имеет шаблон, данные в списке всегда различны, но это не случайное.
@Trimax В моем конкретном случае я не против, если словарь не в правильном порядке. Но если мне так нужно, я воспользуюсь твоим предложением. Спасибо.
>>> import re >>> import ast >>> entities = ["#1= IFCORGANIZATION('$','Autodesk Revit 2014 (ENU)','$','$','$');", "#5= IFCAPPLICATION('#1','2014','Autodesk Revit 2014 (ENU)','Revit');"] >>> entities = [a.strip(';') for a in entities] >>> pattern = re.compile(r'\((.*)\)') >>> dic = <> >>> for a in entities: . s = re.search(pattern, a) . dic[a[:a.index(s.group(0))]] = list(ast.literal_eval(s.group(0))) >>> dic
Это регулярное выражение r’\((.*)\)’ Ищет элементы в ( и ) и преобразует их в список. Это приводит к тому, что подстрока появляется перед скобками в качестве ключа и списка в качестве значения.
Shaktimaan: Спасибо за вашу быструю поддержку. Я не знал этих модулей, поэтому спасибо, что познакомили меня с ними. Мне не удалось заставить ваш код работать, потому что в моей переменной «entity» у меня нет ‘наряду с $, то есть’ $ ‘. Но я думаю, что с некоторыми изменениями все будет хорошо! С уважением.