def get_frequencies(filename: str) -> None:
'''
1. Open a text file.
2. Read all its lines.
3. Turn each line to lower case (use .lower() )
4. Ignore any letters that are not a-z (use string.ascii_lower)
5. Compute the counts for each letter
6. Go through all the letters,
6. Compute the frequency of each letter.
7. Print the letter, and its frequency.
Parameter:
---------
filename: the name of the text file
'''
text = open(filename, 'r')
letters = text.ascii_lower
for i in text:
text_lower = i.lower()
text_nospace = text_lower.replace(" ", "")
text_nopunctuation = text_nospace.strip(string.punctuation)
for a in letters:
if a in text_nopunctuation:
num = text_nopunctuation.count(a)
print(a, num)
这是我在运行代码时得到的回溯:
Traceback (most recent call last):
File "C:/MyPython/Code/StackOverflow-Questions/get_frequencies-Broken.py", line 28, in <module>
get_frequencies('test1.txt')
File "C:/MyPython/Code/StackOverflow-Questions/get_frequencies-Broken.py", line 18, in get_frequencies
letters = text.ascii_lower
AttributeError: '_io.TextIOWrapper' object has no attribute 'ascii_lower'
您需要导入字符串,并且需要为字母变量指定string.ascii_小写
以下是一个工作版本:
相关问题 更多 >
编程相关推荐