请编写一个函数,统计某一个单词在一个英文文本文件(如article txt)中出现的次数。所谓单词,即连续的字母串,例在“how are you!”中,how、are、you都是单词,而howare或you! 都不是。
file_name ="article.txt"
line_counts =0 #行数
word_counts =0 #个数
character_counts =0 #字符数
with open(file_name, 'r',encoding='utf-8')as f:
for line in f:
words = line.split()#split()用于分割,分隔符可以自己制定
line_counts +=1
word_counts +=len(words)
character_counts +=len(line)
print ("word_counts ", word_counts)
如果有帮助请点一下我回答右上方的采纳,谢谢!以后有什么问题可以互相交流。
# 统计单词出现次数并把结果输出成字典
# 数据输入
str = "Hello world, There are some test words. Hello world, There are some test words. Haha!"
# 过滤规则:过滤掉所有非字母的字符
import re
str = re.sub(r"[^a-zA-Z]+", " ",str)
print("过滤后的字符串:",str)
#拆分成列表
str = str.split(" ")
# 去除多余的空项
str.remove("")
print("拆分成列表:",str)
# 生成字典的key列表
dict_keys = []
for i in str:
if i not in dict_keys:
dict_keys.append(i)
print("key列表:",dict_keys)
# 输出字典
# 定义空字典
words_dict = {}
# 往字典写入key值
words_dict.fromkeys(dict_keys)
# 遍历key列表,利用count函数统计单词出现次数
for j in dict_keys:
words_dict[j] = str.count(j)
print("字典:",words_dict)
参考一下,如果对你有帮助,可以点击我这个回答右上方的【采纳】按钮,给我个采纳吗,谢谢
import re
def f(file, t):
with open(file, 'r') as f:
s = f.read() # 读取文档
s = re.sub('[,.?!\n]','',s).split(' ') # 去除其中的符号
return s.count(t) # 统计出现的次数
f('article.txt', 'how')
建议使用numpy库中的np.counter中的most_common()