【问题标题】:count the numbers of words only from string in python [closed]仅从python中的字符串计算单词数[关闭]
【发布时间】:2021-03-20 03:15:27
【问题描述】:
txt = "The rain in Spain3 3545 & %"

count = len(re.findall(r'\w+', txt))

print (count)

输出=5

所需的输出是 3 。单词“The”、“rain”、“in”这些只需要计算。 程序不计算特殊字符而是计算数字。如何也可以删除数字并只计算单词

【问题讨论】:

  • 你想要的结果是什么? Spain3 应该算吗?像2nd 这样的词呢? isn't 这样的词怎么样?
  • 应该从您的样本输入中计算出多少个实际“单词”?
  • 想要的输出是3,带数字或特殊字符的单词也需要去掉

标签: python-3.x regex string list count


【解决方案1】:

您可以尝试计算匹配 \b[A-Za-z]+\b 的词条数:

txt = "The rain in Spain3 3545 & %"
matches = re.findall(r'\b[A-Za-z]+\b', txt)
print(len(matches))  # 3

另一方面,如果您想将一个单词定义为任意数量的字母数字字符,只要至少存在一个字母,那么您可以将上述方法与模式 \b\w*[A-Za-z]\w*\b 一起使用:

txt = "The rain in Spain3 3545 & %"
matches = re.findall(r'\b\w*[A-Za-z]\w*\b', txt)
print(len(matches))  # 4

【讨论】:

    猜你喜欢
    • 2018-04-02
    • 2014-01-02
    • 1970-01-01
    • 2013-02-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    相关资源
    最近更新 更多