【问题标题】:How to also remove whitespace with this regular expression?如何使用此正则表达式删除空格?
【发布时间】:2021-03-08 18:02:13
【问题描述】:

给我一​​个文本(带有标点符号),我需要计算每个单词在其中出现的次数。我想这样做如下:我想将单词与其他字符分开,然后我想创建一个频率表。这是我的代码:

import re
text=input("Input:")
space={''}
text=re.split("[. | , | ! | ?| |]", text)
sett=set(text)-space
frequency_table={}
for element in sett:
     frequency_table[element]=text.count(element)
print(frequency_table)

这可以解决问题,但我的问题是我无法找到一种方法让我的正则表达式从一开始就删除空格。我发现了这个非常奇怪的解决方案,但我不知道,它感觉不“正确”,应该有一种方法也可以使用该正则表达式删除空格。
编辑:这是一个示例输入和一个示例输出:

Input: Bob?...Bob has many, many apples!... But you, how many apples do you have?
Output: Bob:2
        has:1
        many:3
        apples:2
        But:1
        you:2
        how:1
        do:1
        have:1

注意:输出中单词的顺序无关紧要,我不在乎它们是如何排序的。

【问题讨论】:

  • 您能否包括一些示例输入以及预期输出。
  • @sushanth 当然,我会马上加入。
  • “从头开始删除空格” - text.lstrip()?
  • @WiktorStribiżew 我以前没有见过这个功能,所以我不确定我应该如何使用它。我试图把它放在 text=re.split("[. | , | ! | ?| |]", text) 上面,但它似乎没有做任何事情。
  • 为什么不直接使用Counter(re.findall(r'\w+', text))Counter(re.findall(r'[^\W_]+', text))?为什么要处理标点符号?

标签: python python-3.x regex split


【解决方案1】:

Imo,您可以使用相反的方法 - 定义“单词”是什么并使用 defaultdict。这可能是:

import re
from collections import defaultdict

# pattern and container
rx = re.compile(r'\b[-\w]+\b')
dd = defaultdict(int)

text = "Bob?...Bob has many, many apples!... But you, how many apples do you have?"

for word in rx.finditer(text):
    dd[word.group(0)] += 1
    
print(dd)

这会导致

defaultdict(<type 'int'>, {'do': 1, 'many': 3, 'But': 1, 'how': 1, 'apples': 2, 'have': 1, 'Bob': 2, 'has': 1, 'you': 2})

【讨论】:

    【解决方案2】:

    您可以在这里尝试另一种解决方案,

    import re
    from string import punctuation
    from collections import Counter
    
    input_ = "Bob?...Bob has many, many apples!... But you, how many apples do you have?"
    
    re_ = re.compile("|".join(re.escape(i) for i in punctuation))
    
    for k, v in Counter(re_.sub(" ", input_).split()).items():
        print(k, v)
    

    Bob 2
    has 1
    many 3
    apples 2
    ...
    ...
    

    【讨论】:

    • 谢谢!这绝对有效。你知道我怎么做我提到的那个特定的调整吗?
    【解决方案3】:

    使用

    import re
    from collections import Counter
    
    results = Counter(re.findall(r"[^\W_]+", "Bob?...Bob has many, many apples!... But you, how many apples do you have?"))
    print(results)
    

    结果Counter({'many': 3, 'Bob': 2, 'apples': 2, 'you': 2, 'has': 1, 'But': 1, 'how': 1, 'do': 1, 'have': 1})

    Python proof

    [^\W_]+ 匹配除非单词字符以外的任何字符(除了a-zA-Z0-9_)、_ 之外的所有字符(1 次或多次(匹配尽可能多的次数)) .

    【讨论】:

      猜你喜欢
      • 2020-09-03
      • 2012-03-20
      • 2011-11-01
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多