- AttributeError: ‘list’ object has no attribute ‘lower’ with CountVectorizer
- How to Solve Python AttributeError: ‘list’ object has no attribute ‘lower’
- Table of contents
- AttributeError: ‘list’ object has no attribute ‘lower’
- Python lower() Syntax
- Example
- Solution
- Summary
- Share this:
- How to resolve AttributeError: ‘list’ object has no attribute ‘lower’ in Python
- What causes the AttributeError: ‘list’ object has no attribute ‘lower’?
- How to solve the AttributeError: ‘list’ object has no attribute ‘lower’?
- Convert the list to a string.
- Access the list index and then use the lower() function.
- Use list comprehension or for loop.
- Summary
- Attributeerror: list object has no attribute lower ( Solved )
- Attributeerror: list object has no attribute lower: Root cause
- The solution of the list object has no attribute lower error
- Conclusion
AttributeError: ‘list’ object has no attribute ‘lower’ with CountVectorizer
I am trying to make a prediction on a pandas dataframe in Python. Somehow the CountVectorizer can’t convert the data. Does anyone know what’s causing the problem? This is my code:
filename = 'final_model.sav' print(response.status_code) data = response.json() print(data) dictionary = pd.read_json('rating_company_small.json', lines=True) dictionary_df = pd.DataFrame() dictionary_df["comment text"] = dictionary["comment"] data = pd.DataFrame.from_dict(json_normalize(data), orient='columns') print(data) df = pd.DataFrame() df["comment text"] = data["Text"] df["status"] = data["Status"] print(df) Processing.dataframe_cleaning(df) comment_data = df['comment text'] tfidf = CountVectorizer() tfidf.fit(dictionary_df["comment text"]) Test_X_Tfidf = tfidf.transform(df["comment text"]) print(comment_data) print(Test_X_Tfidf) loaded_model = pickle.load(open(filename, 'rb')) predictions_NB = loaded_model.predict(Test_X_Tfidf)
comment text status 0 [slecht, bedrijf] string 1 [leuk, bedrijfje, goed, behandeld] Approved 2 [leuk, bedrijfje, goed, behandeld] Approved 3 [leuk, bedrijfje] Approved
Traceback (most recent call last): File "Request.py", line 36, in Test_X_Tfidf = tfidf.transform(df["comment text"]) File "C:\Users\junio\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 1112, in transform _, X = self._count_vocab(raw_documents, fixed_vocab=True) File "C:\Users\junio\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 970, in _count_vocab for feature in analyze(doc): File "C:\Users\junio\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 352, in tokenize(preprocess(self.decode(doc))), stop_words) File "C:\Users\junio\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 256, in return lambda x: strip_accents(x.lower()) AttributeError: 'list' object has no attribute 'lower'
How to Solve Python AttributeError: ‘list’ object has no attribute ‘lower’
In Python, the list data structure stores elements in sequential order. We can use the String lower() method to get a string with all lowercase characters. However, we cannot apply the lower() function to a list. If you try to use the lower() method on a list, you will raise the error “AttributeError: ‘list’ object has no attribute ‘lower’”.
This tutorial will go into detail on the error definition. We will go through an example that causes the error and how to solve it.
Table of contents
AttributeError: ‘list’ object has no attribute ‘lower’
AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The part “‘list’ object has no attribute ‘lower’” tells us that the list object we are handling does not have the lower attribute. We will raise this error if we try to call the lower() method on a list object. lower() is a string method that returns a string with all lowercase characters.
Python lower() Syntax
The syntax for the String method lower() is as follows:
The lower() method ignores symbols and numbers.
Let’s look at an example of calling the lower() method on a string:
a_str = "pYTHoN" a_str = a_str.lower() print(a_str)
Next, we will see what happens if we try to call lower() on a list:
a_list = ["pYTHoN", "jAvA", "ruBY", "RuST"] a_list = a_list.lower() print(a_list)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) 1 a_list = ["pYTHoN", "jAvA", "ruBY", "RuST"] 2 ----≻ 3 a_list = a_list.lower() 4 5 print(a_list) AttributeError: 'list' object has no attribute 'lower'
The Python interpreter throws the Attribute error because the list object does not have lower() as an attribute.
Example
Let’s look at an example where we read a text file and attempt to convert each line of text to all lowercase characters. First, we will define the text file, which will contain a list of phrases:
CLiMBinG iS Fun RuNNing is EXCitinG SwimmING iS RElaXiNg
We will save the text file under phrases.txt . Next, we will read the file and apply lower() to the data:
data = [line.strip() for line in open("phrases.txt", "r")] print(data) text = [[word for word in data.lower().split()] for word in data] print(text)
The first line creates a list where each item is a line from the phrases.txt file. The second line uses a list comprehension to convert the strings to lowercase. Let’s run the code to see what happens:
['CLiMBinG iS Fun', 'RuNNing is EXCitinG', 'SwimmING iS RElaXiNg'] --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) 1 data = [line.strip() for line in open("phrases.txt", "r")] 2 print(data) ----≻ 3 text = [[word for word in data.lower().split()] for word in data] 4 print(text) AttributeError: 'list' object has no attribute 'lower'
The error occurs because we applied lower() to data which is a list. We can only call lower() on string type objects.
Solution
To solve this error, we can use a nested list comprehension, which is a list comprehension within a list comprehension. Let’s look at the revised code:
data = [line.strip() for line in open("phrases.txt", "r")] print(data) text = [[word.lower() for word in phrase.split()] for phrases in data] print(text)
The nested list comprehension iterates over every phrase, splits it into words using split() , and calls the lower() method on each word. The result is a nested list where each item is a list that contains the lowercase words of each phrase. Let’s run the code to see the final result:
['CLiMBinG iS Fun', 'RuNNing is EXCitinG', 'SwimmING iS RElaXiNg'] [['climbing', 'is', 'fun'], ['running', 'is', 'exciting'], ['swimming', 'is', 'relaxing']]
If you want to flatten the list you can use the sum() function as follows:
flat_text = sum(text, []) print(flat_text)
['climbing', 'is', 'fun', 'running', 'is', 'exciting', 'swimming', 'is', 'relaxing']
There are other ways to flatten a list of lists that you can learn about in the article: How to Flatten a List of Lists in Python.
If we had a text file, where each line is a single word we would not need to use a nested list comprehension to get all-lowercase text. The file to use, words.txt contains:
CLiMBinG RuNNing SwimmING
The code to use is as follows:
text = [word.lower() for word in open('words.txt', 'r')] print(text)
Let’s run the code to see the output:
['climbing', 'running', 'swimming']
Summary
Congratulations on reading to the end of this tutorial! The error “AttributeError: ‘list’ object has no attribute ‘lower’” occurs when you try to use the lower() function to replace a string with another string on a list of strings.
The lower() function is suitable for string type objects. If you want to use the lower() method, ensure that you iterate over the items in the list of strings and call the lower method on each item. You can use list comprehension to access the items in the list.
Generally, check the type of object you are using before you call the lower() method.
For further reading on AttributeErrors involving the list object, go to the articles:
To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.
Have fun and happy researching!
Share this:
How to resolve AttributeError: ‘list’ object has no attribute ‘lower’ in Python
While there are times when you will inevitably mistake function calls on data types for which it is not allowed, that is also the cause of the error AttributeError: ‘list’ object has no attribute ‘lower’. The following article will help you find a solution to this error. Hope you will read the whole article.
What causes the AttributeError: ‘list’ object has no attribute ‘lower’?
The error happens because you call lower() on a list instead of you calling it on a string.
The lower() function syntax:
The str.lower() function returns a string that converts all uppercase to lowercase.
uppercaseList = ['VISIT', 'LEARNSHAREIT', 'WEBSITE'] # Call the lower() method on the list print(uppercaseList.lower())
Traceback (most recent call last): File "./prog.py", line 4, in AttributeError: 'list' object has no attribute 'lower'
How to solve the AttributeError: ‘list’ object has no attribute ‘lower’?
Convert the list to a string.
If you have a list that you want to use the lower() function on, convert the list to a string first.
uppercaseList = ['VISIT', 'LEARNSHAREIT', 'WEBSITE'] # Use the join() function to convert a list to a string listConvertToStr = ' '.join(uppercaseList) print(listConvertToStr) print(type(listConvertToStr)) # The lower() function converts uppercase letters to lowercase letters print(listConvertToStr.lower())
VISIT LEARNSHAREIT WEBSITE visit learnshareit website
Access the list index and then use the lower() function.
- You can use the index to access each element in the list and then call lower() on each of those elements.
- Note: The list index starts from 0 and ends with the length of the list – 1.
uppercaseList = ['VISIT', 'LEARNSHAREIT', 'WEBSITE'] # Access the index and call lower() on the indexes print(uppercaseList[0].lower()) print(uppercaseList[1].lower()) print(uppercaseList[2].lower())
visit learnshareit website
Use list comprehension or for loop.
Using list comprehension or for loop are also good ideas to fix the error.
uppercaseList = ['VISIT', 'LEARNSHAREIT', 'WEBSITE'] # Use list comprehension and lower() function lowerList = [i.lower() for i in uppercaseList] print(lowerList)
['visit', 'learnshareit', 'website']
uppercaseList = ['VISIT', 'LEARNSHAREIT', 'WEBSITE'] # Use for loop and lower() function for i in uppercaseList: lowerList = i.lower() print(lowerList)
visit learnshareit website
Summary
Through this article, you have an idea to fix the AttributeError: ‘list’ object has no attribute ‘lower’ in Python. Use the list comprehension or for loop 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
Attributeerror: list object has no attribute lower ( Solved )
A list is used to store multiple variables in a single variable. If you are using the lower() function on the list of strings, you may encounter the error Attributeerror: list object has no attribute lower. In this example, you will learn how to solve this issue and how to convert the list of strings to lowercase.
Attributeerror: list object has no attribute lower: Root cause
The root cause of this error is that you are using the lower() function on the wrong object. You are applying this function on the list which is wrong. Let’s apply the lower() function on the list of strings.
You will get the Attributeerror: list object has no attribute lower after running the below lines of code.
AttributeError: 'list' object has no attribute 'lower'
The solution of the list object has no attribute lower error
The simple solution to solve this error is that you must use the lower() function on the strings on the list. For example, If I use the lower() function on the below string it will convert all its characters to lowercase.
If you want to change all the string elements of the list then you have to iterate the list. Execute the below lines of code to convert the elements of the string to lowercase.
In the above code, I used list comprehension to iterate the list of strings. Also, you are not getting the Attributeerror: list object has no attribute lower error.
Conclusion
The lower() function works on the string data type. If you are invoking on the list then you will get the attributeError on it. To solve the issue you have to iteration on the list and convert each string value to lowercase. In this tutorial, we have written the same solution. Hope this post has solved the error.