【问题标题】:How can I count phrases and use the phrases as headers in Python?如何计算短语并将短语用作 Python 中的标题?
【发布时间】:2013-02-26 20:01:46
【问题描述】:

我有一个文件,我试图在其中获取短语计数。在某些文本行中,我需要计算大约 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

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

【问题讨论】:

    标签: python text count


    【解决方案1】:

    创建标题列表

    In [6]: p=phrases.strip().split('\n')
    
    In [7]: p
    Out[7]: ['hello', 'name', 'john doe']
    

    使用word-boundaries\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() 以获得找到的模式数量。

    【讨论】:

    • 非常感谢。这正是我所需要的。
    【解决方案2】:

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

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

    所以这应该可以工作(除了下面的 cmets 中提到的不匹配)

    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]
    

    【讨论】:

    • 太好了。我知道这一定很简单。我试图用空格分割文本,结果一团糟。谢谢!
    • 在这种情况下单独使用.count() 可能会因为意外匹配而变得危险。例如,考虑“奥赛罗”或“珐琅”。
    • @DSM 是的,我想解决方案是使用正则表达式,但我无能为力。
    【解决方案3】:

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

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

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

    然后让您在创建标头时跳过循环:

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

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

    【讨论】:

    • @myname 不用担心,希望对您有所帮助
    【解决方案4】:
    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
    

    【讨论】:

      猜你喜欢
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多