Python文本文件词频统计报错:无法将字符串转为float问题求助
问题描述
需要统计纯单词文本文件中出现频率最高的单词及频次,但沿用处理数字文件的逻辑(用float()转换内容)时触发报错。
尝试的错误代码
words = {} myfile = open("HAPPY.txt") for x in myfile: y = float(x.strip()) if y not in words: words[y] = 1 else: words[y] = words[y] + 1 for x in words: if words[x] == max(words.values()): print(x, words[x])
报错信息
Traceback (most recent call last): File "C:\Users\jekni\PycharmProjects\Python Class\Homework\HW 7.py", line 31, in <module> y = float(x.strip()) ^^^^^^^^^^^^^^^^ ValueError: could not convert string to float: 'Once upon a time in a faraway land there lived a man and a woman'
相关样本内容
单词文件样本
Once upon a time in a faraway land there lived a man and a woman
They lived in a humble cottage in the heart of the woods where they found peace and happiness in the simplicity of their life
此前可正常处理的数字文件样本
69
35
31
75
87
56
55
67
30
解决方案
问题出在哪
原代码犯了两个核心错误:
- 把整行包含多个单词的文本直接用
float()转换,单词本身没法转成浮点数,自然报错。 - 没有拆分每行里的单个单词,而是把整行当成一个统计对象,完全不符合需求。
修正后的代码
word_counts = {} # 用with语句自动管理文件关闭,更稳妥 with open("HAPPY.txt", "r") as myfile: for line in myfile: # 拆分每行的单词:先清首尾空白,再按空格拆成单个单词 words = line.strip().split() for word in words: # 统计频次,get方法直接处理单词不存在的情况,不用写if-else word_counts[word] = word_counts.get(word, 0) + 1 # 找到最高出现频次 max_count = max(word_counts.values()) # 输出所有频次最高的单词(可能有多个并列) for word, count in word_counts.items(): if count == max_count: print(f"{word}: {count}")
代码说明
- 文件管理:
with语句会在代码块结束后自动关闭文件,避免忘记关文件导致的资源问题。 - 单词拆分:
strip()去掉每行首尾的换行、空格,split()默认按任意空白(空格、制表符等)拆分出单个单词。 - 频次统计:
dict.get(key, default)方法如果key不存在就返回默认值0,加1后赋值,比原有的if-else写法更简洁。 - 结果输出:先拿到所有频次里的最大值,再遍历字典找出所有等于这个值的单词,处理多个单词并列第一的情况。
内容的提问来源于stack exchange,提问作者jeknightx95
相关产品推荐
相关产品推荐

