Python - 查找文本文件中字符串列表的字符串频率
Python - Finding string frequencies of list of strings in text file
我正在尝试查找文本文件中出现的所有字符串,其中每个字符串都位于文件中的新行上。
例如,示例文件可能如下所示:
jump start
jump go
feet start
jump go
所有字符串的目标计数为 1,除了 "jump go" 为 2
到目前为止,我已经成功地使用以下代码找到了单个字数:
import re
import collections
with open('file.txt') as f:
text = f.read()
words = re.findall(r'\w+',text)
counts = collections.Counter(words)
print(counts)
但是,这只会给出如下输出:jump = 3, start = 2, go = 2, feet = 1
不确定这是否重要,但文件中的行数大约为 500 万行,包含大约 12,000 个独立字符串。
感谢您的帮助!
不使用正则表达式,而是将文件读取为 words=f.readlines()
。您最终会得到与每一行对应的字符串列表。然后,从该列表构建计数器。
我成功了:
import collections
lines = [line.strip() for line in open('results.txt')]
counts = collections.Counter(lines)
print counts
输出:
['Sam', 'sam', 'johm go', 'johm go', 'johm for']
Counter({'johm go': 2, 'sam': 1, 'Sam': 1, 'johm for': 1})
我正在尝试查找文本文件中出现的所有字符串,其中每个字符串都位于文件中的新行上。
例如,示例文件可能如下所示:
jump start
jump go
feet start
jump go
所有字符串的目标计数为 1,除了 "jump go" 为 2
到目前为止,我已经成功地使用以下代码找到了单个字数:
import re
import collections
with open('file.txt') as f:
text = f.read()
words = re.findall(r'\w+',text)
counts = collections.Counter(words)
print(counts)
但是,这只会给出如下输出:jump = 3, start = 2, go = 2, feet = 1
不确定这是否重要,但文件中的行数大约为 500 万行,包含大约 12,000 个独立字符串。
感谢您的帮助!
不使用正则表达式,而是将文件读取为 words=f.readlines()
。您最终会得到与每一行对应的字符串列表。然后,从该列表构建计数器。
我成功了:
import collections
lines = [line.strip() for line in open('results.txt')]
counts = collections.Counter(lines)
print counts
输出:
['Sam', 'sam', 'johm go', 'johm go', 'johm for']
Counter({'johm go': 2, 'sam': 1, 'Sam': 1, 'johm for': 1})