获取错误'\u io.TextIOWrapper'对象没有属性'ascii\u lower'

2024-04-26 10:45:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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'

Tags: thetextinforgetlineasciifilename
1条回答
网友
1楼 · 发布于 2024-04-26 10:45:07

您需要导入字符串,并且需要为字母变量指定string.ascii_小写

以下是一个工作版本:

import string

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 = string.ascii_lowercase
    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)

相关问题 更多 >