简体   繁体   中英

Calculate the frequency for each word in text file, store it in a variable using python

but without the help of inbuilt counter function

with open(r"C:\\Users\\muizv\\Desktop\\alice_in_wonderland.txt", "rt") as f:

you can read the content of the file: content = f.read() , then use regex to find all words words = re.findall(r'[a-zA-Z]+', content) then loop over the list and use a dict to count the words:

freq = {}
for word in words:
    freq[word] = freq.get(word, 0) + 1 # adds 1 to the freq of the current word, with 0 as the default
console.log(freq)

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