1

我有一个文件,我试图在其中获取短语计数。在某些文本行中,我需要计算大约 100 个短语。作为一个简单的例子,我有以下内容:

phrases = """hello
name
john doe
"""

text1 = 'id=1: hello my name is john doe.  hello hello.  how are you?'
text2 = 'id=2: I am good.  My name is Jane.  Nice to meet you John Doe'

header = ''
for phrase in phrases.splitlines():
    header = header+'|'+phrase
header = 'id'+header

我希望能够得到如下所示的输出:

id|hello|name|john doe
1|3|1|1
2|0|1|1

我把标题放下了。我只是不确定如何计算每个短语并附加输出。

4

4 回答 4

3

创建标题列表

In [6]: p=phrases.strip().split('\n')

In [7]: p
Out[7]: ['hello', 'name', 'john doe']

使用使用单词边界的正则表达式,即\b获得避免部分匹配的出现次数。该标志re.I是使搜索不区分大小写。

In [11]: import re

In [14]: re.findall(r'\b%s\b' % p[0], text1)
Out[14]: ['hello', 'hello', 'hello']

In [15]: re.findall(r'\b%s\b' % p[0], text1, re.I)
Out[15]: ['hello', 'hello', 'hello']

In [16]: re.findall(r'\b%s\b' % p[1], text1, re.I)
Out[16]: ['name']

In [17]: re.findall(r'\b%s\b' % p[2], text1, re.I)
Out[17]: ['john doe']

在它周围放一个len()以获得找到的模式数量。

于 2013-02-26T20:15:42.540 回答
2

您可以使用来计算字符串中的单词.count()

>>> text1.lower().count('hello')
3

所以这应该有效(除了下面评论中提到的不匹配)

phrases = """hello
name
john doe
"""

text1 = 'id=1: hello my name is john doe.  hello hello.  how are you?'
text2 = 'id=2: I am good.  My name is Jane.  Nice to meet you John Doe'

texts = [text1,text2]

header = ''
for phrase in phrases.splitlines():
    header = header+'|'+phrase
header = 'id'+header
print header

for id,text in enumerate(texts):
    textcount = [id]
    for phrase in header.split('|')[1:]:
        textcount.append(text.lower().count(phrase))
    print "|".join(map(str,textcount))

上面假设你有一个按它们id的顺序排列的文本列表,但如果它们都以你的开头,'id=n'你可以这样做:

for text in texts:
    id = text[3]  # assumes id is 4th char
    textcount = [id]
于 2013-02-26T20:05:21.490 回答
0

虽然它没有回答你的问题(@askewchan 和 @Fredrik 已经这样做了),但我想我会就你的其余方法提供一些建议:

通过在列表中定义您的短语可能会更好地为您服务:

phrases = ['hello', 'name', 'john doe']

然后,您可以跳过创建标头的循环:

header = 'id|' + '|'.join (phrases)

并且您可以.split ('|')[1:] 省略 askewchan 答案中的部分,例如,只支持for phrase in phrases:

于 2013-02-26T20:19:13.107 回答
0
phrases = """hello
name
john doe
"""

text1 = 'id=1: hello my name is john doe.  hello hello.  how are you?'
text2 = 'id=2: I am good.  My name is Jane.  Nice to meet you John Doe'

import re
import collections

txts = [text1, text2]
phrase_list = phrases.split()
print "id|%s" % "|".join([ p for p in phrase_list])
for txt in txts:
    (tid, rest) = re.match("id=(\d):\s*(.*)", txt).groups()

    counter = collections.Counter(re.findall("\w+", rest))
    print "%s|%s" % ( tid, "|".join([str(counter.get(p, 0)) for p in phrase_list]))

给出:

id|hello|name|john|doe
1|3|1|1|1
2|0|1|0|0
于 2013-02-26T20:37:52.767 回答