简体   繁体   中英

How to fix "TypeError: 'str' object is not callable" error in Python?

I'm trying to rank words used in one document by their frequency in another document.

As I am a beginner, I asked someone to help me with the code, and this is what they sent me. It's giving me an error.

from collections import defaultdict
occurences = defaultdict(int)
with open("booksandtranscripts.txt","r") as file:
    booksandtranscripts = file.read()
    for word in booksandtranscripts.split(" "):
        occurences[word] += 1
words_and_frequencies = []
with open("allminow.txt","r") as file:
    allminow = file.read()
    for word in allminow.split(" "):
        words_and_frequencies.append((occurences[word],[word]))
for frequency,word in sorted(words_and_frequencies):
    print("%s : %i %" (word, frequency))

I expected it to print the words of one document alongside them the frequencies of those words in the other document. I know this code doesn't export csv, but I was planning on attempting to add that too.

Here is the error I got:

Traceback (most recent call last):
  line 15, in <module>
    print("%s : %i %" (word, frequency))
TypeError: 'str' object is not callable

your print format is wrong:

Basic formatting Simple positional formatting is probably the most common use-case. Use it if the order of your arguments is not likely to change and you only have very few elements you want to concatenate.

Since the elements are not represented by something as descriptive as a name this simple style should only be used to format a relatively small number of elements.

Old

print("%s : %i %%" % (word, frequency)) # To print the % sign you need to 'escape' it with another % sign

New

print ('{} : {} %'.format(word, frequency))

print(f"{word} : {frequency} %")

I think the error is in the syntax of the print string representing the variables. I don't understand the c-style %-thing, so I just suggest to use the current f-string syntax instead:

print(f"{word}: {frequency} %")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM