[英]Count all occurrences of elements with and without special characters in a list from a text file in python
如果以前已经回答过这个问题,我真的很抱歉,但是我一直在搜索SO和Google几个小时,以了解如何正确执行此操作。 这应该很容易,我知道我缺少一些简单的东西。
我正在尝试从文件中读取内容并计算列表中元素的所有出现次数。 但是,这个列表并不只是完整的单词。 它也需要具有特殊字符和标点符号。
这是到目前为止,我一直在尝试各种方法,而这篇文章使我最接近: Python-查找文本文件中单词列表的单词频率
所以我有一个包含几个段落的文件,我的字符串列表是:
listToCheck = ['the','The ','the,','the;','the!','the\'','the.','\'the']
我的完整代码是:
#!/usr/bin/python
import re
from collections import Counter
f = open('text.txt','r')
wanted = ['the','The ','the,','the;','the!','the\'','the.','\'the']
words = re.findall('\w+', f.read().lower())
cnt = Counter()
for word in words:
if word in wanted:
print word
cnt[word] += 1
print cnt
到目前为止,我的输出看起来像:
the
the
the
the
the
the
the
the
the
the
the
the
the
the
the
the
the
Counter({'the': 17})
它使用标点符号计数我的“ the”字符串,但不将其作为单独的计数器计数。 我知道是因为\\ W +。 我只是不确定在这里使用什么合适的正则表达式模式,或者我是否打算使用错误的方式。
我怀疑您的特定问题可能还有一些其他细节,为简单起见,在此不再赘述。 但是,我假设您要查找的是找到给定的单词,例如“ the”,该单词可以具有大写或小写的首字母,并且可以在其前后加上空格或标点符号;,。!'等字符。 您要计算该常规模式的所有不同实例的数量。
我将定义一个单个(非析取式)正则表达式来定义它。 像这样
import re
pattern = re.compile(r"[\s',;.!][Tt]he[\s.,;'!]")
(一般来说,这可能与您所寻找的不完全相同。我只是假设它基于您上面所说的内容。)
现在,假设我们的文字是
text = '''
Foo and the foo and ;the, foo. The foo 'the and the;
and the' and the; and foo the, and the. foo.
'''
我们可以做
matches = pattern.findall(text)
比赛将在哪里
[' the ',
';the,',
' The ',
"'the ",
' the;',
" the'",
' the;',
' the,',
' the.']
然后,您只需数数即可。
from collections import Counter
count = Counter()
for match in matches:
count[match] += 1
在这种情况下会导致
Counter({' the;': 2, ' the.': 1, ' the,': 1, " the'": 1, ' The ': 1, "'the ": 1, ';the,': 1, ' the ': 1})
正如我刚开始所说的那样,这可能并不是您想要的,但是希望您可以对其进行修改以获得所需的内容。
补充一点,使用析取正则表达式(例如
'the|the;|the,|the!'
是像“ the”和“ the;”这样的字符串 也将匹配第一个选项,即“ the”,并将其作为匹配项返回。 即使可以通过更仔细地选择选项来避免此问题,但我认为总体上可能并不容易。
最简单的选择是将所有“需要的”字符串组合成一个正则表达式:
rr = '|'.join(map(re.escape, wanted))
然后使用re.findall
查找文本中的所有匹配re.findall
。
要确保更长的st先匹配,只需将wanted
列表按长度排序:
wanted.sort(key=len, reverse=True)
rr = '|'.join(map(re.escape, wanted))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.