【问题标题】:Count frequency of a letter in text file without using built-in dict data structure OR count function in Python在不使用 Python 内置的 dict 数据结构或计数函数的情况下计算文本文件中字母的频率
【发布时间】:2016-10-23 23:14:48
【问题描述】:

我正在开发一个计算文本文件中单词和字母数量的程序。该程序还应显示文件中每个字母的使用次数。我已经包含了用于计算单词和字母的代码。我需要帮助找到显示字母频率的最佳方式,而不使用 count 或 dict 函数。

f=open ("C:\\Users\\Adam\\Documents\\romeo.txt",'r')

num_lines = 0
num_words = 0
num_char = 0


with open("C:\\Users\\Adam\\Documents\\romeo.txt", 'r') as f:
    for line in f:
        words = line.split()


        num_lines += 1
        num_words += len(words)
        num_char+=  sum(len(x) for x in line.split())

【问题讨论】:

  • 有什么问题?你的代码有效吗?
  • 在找到有点主观的“最佳”方式之前,请尝试至少找到一种方式。然后分享它,如果它不起作用并且你不知道为什么。我在这里没有看到任何尝试...
  • 不需要初始 f=open(....) 并且您的缩进很糟糕。这甚至可以运行吗?

标签: python count frequency letter


【解决方案1】:

您的代码只需稍作调整即可使用。试试这个:

number_of_lines = 0
number_of_words = 0
number_of_chars = 0

with open(r'myfile.txt', 'r') as f:
    for line in f:
        number_of_lines += 1
        word_list = line.split()
        number_of_words += len(word_list)
        number_of_chars += sum(len(x) for x in word_list)

【讨论】:

    【解决方案2】:

    改用此代码

    f=open()
    num_lines = 0
    num_words = 0
    num_char = 0s
    
    while str:
        str=f.readline()
        words=str.split()
        num_words+=len(words)
        num_lines+=1
        for a in words:
            num_char+=len(a)
    f.close()
    

    【讨论】:

      猜你喜欢
      • 2015-01-29
      • 2015-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多