Can someone please explain to me why I keep getting this error: TypeError: get_n_nouns() takes 1 positional argument but 2 were given.
I have already had a look at where my problem may be by looking at a similar question (Link) But I have adapted my code going along with the answer and yet I end up with the above error.
Here is the error in full:
Traceback (most recent call last):
File "C:/Users/...../Downloads/Comp4.1/trialTo3.py", line 21, in <module>
app.createPhrases()
File "C:/Users/...../Downloads/Comp4.1/trialTo3.py", line 15, in createPhrases
words = self.get_n_nouns(1)
TypeError: get_n_nouns() takes 1 positional argument but 2 were given
Here is the code:
import csv
class apps():
def get_n_nouns(n):
"""
Returns the n most common nouns
"""
with open("setPhrases.txt") as in_file:
reader = csv.reader(in_file)
data = [[row[0], int(row[1])] for row in list(reader)]
return sorted(data, key=lambda x: -x[1])[:n]
def createPhrases(self):
words = self.get_n_nouns(1)
for word, count in words:
print("{}: {}".format(word, count))
app = apps()
app.createPhrases()
Can someone please explain to me where I am going wrong? Any help is much appreciated.
Ok so I found out where the error was. Kind of a rookie error.
This:
def get_n_nouns(n):
Needed to be written as this:
def get_n_nouns(self, n):
I had forgot to add the self part to it. That is why I kept getting that error message.
Related
I have file names as
When I iterate over them, it iterated in a string manner like:
1
10
11
.
.
19
2
20
.. so on. I hope you got this.
I want to iterate them over as integers not strings. Please help me write a function for it.
for i,file in enumerate(sorted(files),key=lambda x: int(os.path.splitext(file)[0]))
#CODE
But gives an error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-45-f667164b9d6e> in <module>
----> 6 for i,file in enumerate(sorted(files),key=lambda x: int(os.path.splitext(file)[0])):
TypeError: 'key' is an invalid keyword argument for enumerate()
Please help me write a function for it. Thanks in advance.
You might try converting all your files to ints first, then sort them.
import os
files = ['0.pdf', '1.pdf', '12.pdf', '15.pdf', '3.pdf', '2.pdf', ]
for i, file_as_number in enumerate(sorted(int(os.path.splitext(file)[0]) for file in files)):
print(i, file_as_number)
files = ['0.pdf', '1.pdf', '12.pdf', '15.pdf', '3.pdf', '2.pdf' ]
fileDict= {}
SortedFiles = []
for i in range(len(files)):
fileDict[int(files[i].split('.')[0])] = files[i]
for i in sorted(list(fileDict.keys())):
SortedFiles.append(fileDict[i])
print (SortedFiles)
['0.pdf', '1.pdf', '2.pdf', '3.pdf', '12.pdf', '15.pdf']
I have got some direction from this question. I first make the index like below.
import lucene
from org.apache.lucene.analysis.standard import StandardAnalyzer
from org.apache.lucene.index import IndexWriterConfig, IndexWriter, DirectoryReader
from org.apache.lucene.store import SimpleFSDirectory
from java.nio.file import Paths
from org.apache.lucene.document import Document, Field, TextField
from org.apache.lucene.util import BytesRefIterator
index_path = "./index"
lucene.initVM()
analyzer = StandardAnalyzer()
config = IndexWriterConfig(analyzer)
if len(os.listdir(index_path))>0:
config.setOpenMode(IndexWriterConfig.OpenMode.APPEND)
store = SimpleFSDirectory(Paths.get(index_path))
writer = IndexWriter(store, config)
doc = Document()
doc.add(Field("docid", "1", TextField.TYPE_STORED))
doc.add(Field("title", "qwe rty", TextField.TYPE_STORED))
doc.add(Field("description", "uio pas", TextField.TYPE_STORED))
writer.addDocument(doc)
writer.close()
store.close()
I then try to get all the terms in the index for one field like below.
store = SimpleFSDirectory(Paths.get(index_path))
reader = DirectoryReader.open(store)
Attempt 1: trying to use the next() as used in this question which seems to be a method of BytesRefIterator implemented by TermsEnum.
for lrc in reader.leaves():
terms = lrc.reader().terms('title')
terms_enum = terms.iterator()
while terms_enum.next():
term = terms_enum.term()
print(term.utf8ToString())
However, I can't seem to be able to access that next() method.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-47-6515079843a0> in <module>
2 terms = lrc.reader().terms('title')
3 terms_enum = terms.iterator()
----> 4 while terms_enum.next():
5 term = terms_enum.term()
6 print(term.utf8ToString())
AttributeError: 'TermsEnum' object has no attribute 'next'
Attempt 2: trying to change the while loop as suggested in the comments of this question.
while next(terms_enum):
term = terms_enum.term()
print(term.utf8ToString())
However, it seems TermsEnum is not understood to be an iterator by Python.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-48-d490ad78fb1c> in <module>
2 terms = lrc.reader().terms('title')
3 terms_enum = terms.iterator()
----> 4 while next(terms_enum):
5 term = terms_enum.term()
6 print(term.utf8ToString())
TypeError: 'TermsEnum' object is not an iterator
I am aware that my question can be answered as suggested in this question. Then I guess my question really is, how do I get all the terms in TermsEnum?
I found that the below works from here and from test_FieldEnumeration() in the test_Pylucene.py file which is in pylucene-8.6.1/test3/.
for term in BytesRefIterator.cast_(terms_enum):
print(term.utf8ToString())
Happy to accept an answer that has more explanation than this.
This should be quick and easy, I'm just trying to convert some VBA into python and I believe I don't understand how loops work here.
Basically I'm trying to count howmany series there are in a chart, then iterate through those series with for iseries in range(1, nseries):
And I end up getting the following error:
Traceback (most recent call last): File "xx.py", line 10, in
for iseries in range(1, nseries): TypeError: 'method' object cannot be interpreted as an integer
Full script below. The print statements is my attempt at trying to see if the loop worked correctly and counted the correct amount of series/points. That also seems to not work as nothing has been printed, so maybe this is the issue?:
from pptx import Presentation
prs = Presentation('Test.pptx')
for slide in prs.slides:
for shape in slide.shapes:
if not shape.has_chart:
continue
nseries = shape.chart.series.count
print('Series number:', nseries)
for iseries in range(1, nseries):
series = shape.chart.series(iseries)
npoint = series.points.count
print('Point number:', npoint)
prs.save('test3.pptx')
This is likely because count is a function, not an attribute. Try changing the line to:
nseries = shape.chart.series.count()
A better way to loop through the series, however, would be to do it directly instead of using an index:
for series in shape.chart.series:
# do something with series
EDIT: SOLVED--SOURCE CODE HERE: http://matthewdowney20.blogspot.com/2011/09/source-code-for-roku-remote-hack.html
thanks in advance for reading and possibly answering this. So I have a slice of code that looks like this (the commands Down() Select() and Up() are all predefined):
def c1(row):
row_down = row
row_up = row
while row_down > '1':
Down()
row_down = row_down - 1
time.sleep(250)
Select()
time.sleep(.250)
while row_up > '1':
Up()
row_up = row_up - 1
time.sleep(250)
So when I run this with either c1('3') or c1(3) (not jut 3, any number does this) it stops responding, no error or anything, but it executes the first Down() command, and it doesnt seem to get past the row_down = row_down - 1 . So i figure maybe it is stuck on time.sleep(.250), because it isnt executing the Select(), so if i remove time.sleep(.250) from the code i get an error like this:
Traceback (most recent call last):
File "test.py", line 338, in <module>
c1('3')
File "test.py", line 206, in c1
row_down = row_down - 1
TypeError: unsupported operand type(s) for -: 'str' and 'int'
this code snippet is part of a larger program designed for controlling the roku player from a computer, and so far everything has worked but this, which is to automate the typing in the search field, so that you do not have to continually scroll until you find a letter and select. c1(row) would be column 1 row x, if any of you would like the source code for the program over all, i would be happy to send it out. Anyway thanks for listening.
Perhaps you meant
while row_down > 1:
(note 1 is written without quotes). If so, call c1 with c1(3) not c1('3').
Also, in CPython (version 2, but not version 3) integers are comparable to strings, but the answer is not what you might expect:
3 > '1'
# False
When comparing any integer to any string, the integer is always less than string because (believe it or not!) i (as in integer) comes before s (as in string) in the alphabet.
As TokenMacGuy has already pointed out, addition of integers with strings raises a TypeError:
'3' - 1
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
This might explain the error you are seeing when calling c1('3').
>>> x = raw_input('enter a number: ')
enter a number: 5
>>> x
'5'
>>> type(x)
<type 'str'>
>>> x + 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> type(int(x))
<type 'int'>
>>> int(x) + 5
10
>>>
(if you're using python3, use input instead of raw_input)
I suspect that the loop is running with out error because you can subtract from a character to change it: "b - 1 = a". (read edit) It also doesn't error is because, like Marcelo Cantos said in his comment, the first time.sleep is for 250 seconds, not .250 seconds. The error when you remove the time.sleep might be coming up when you subtract past the the ASCII character range since it runs through the loop a lot quicker without the time.sleep.
I hope that helps!
Edit: Actually, I think what I said works in C or something. In python, it doesn't work. The other stuff I said might shed some light though!
I'm trying to simulate a substring in Python but I'm getting an error:
length_message = len(update)
if length_message > 140:
length_url = len(short['url'])
count_message = 140 - length_url
update = update["msg"][0:count_message] # Substring update variable
print update
return 0
The error is the following:
Traceback (most recent call last):
File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 54, in <module>
x.updateTwitterStatus({"url": "http://xxx.com/?cat=49s", "msg": "Searching for some ....... tips?fffffffffffffffffffffffffffffdddddddddddddddddddddddddddddssssssssssssssssssssssssssssssssssssssssssssssssssseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddfffffffffffffffffffffffffffffffffffffffffffff "})
File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 35, in updateTwitterStatus
update = update["msg"][0:count_message]
TypeError: string indices must be integers
I can't do this?
update = update["msg"][0:count_message]
The variable "count_message" return "120"
Give me a clue.
Best Regards,
UPDATE
I make this call, update["msg"] comes from here
x = TwitterC()
x.updateTwitterStatus({"url": "http://xxxx.com/?cat=49", "msg": "Searching for some ...... ....?fffffffffffffffffffffffffffffdddddddddddddddddddddddddddddssssssssssssssssssssssssssssssssssssssssssssssssssseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddfffffffffffffffffffffffffffffffffffffffffffffddddddddddddddddd"})
Are you looping through this code more than once?
If so, perhaps the first time through update is a dict, and update["msg"] returns a string. Fine.
But you set update equal to the result:
update = update["msg"][0:int(count_message)]
which is (presumably) a string.
If you are looping, the next time through the loop you will have an error because now update is a string, not a dict (and therefore update["msg"] no longer makes sense).
You can debug this by putting in a print statement before the error:
print(type(update))
or, if it is not too large,
print(repr(update))