【问题标题】:How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?如何计算句子中的单词数,忽略数字、标点符号和空格?
【发布时间】:2013-10-24 22:58:20
【问题描述】:

我将如何计算一个句子中的单词?我正在使用 Python。

例如,我可能有字符串:

string = "I     am having  a   very  nice  23!@$      day. "

那就是 7 个字。我在每个单词之后/之前以及何时涉及数字或符号时遇到了随机数量的空格问题。

【问题讨论】:

  • 要容纳数字,您可以更改正则表达式。 \w 匹配 [a-zA-Z0-9] 现在,您需要定义您的用例是什么。 I am fine2 会发生什么?是 2 个字还是 3 个字?
  • 您需要明确添加“忽略数字、标点符号和空格”,因为这是任务的一部分。
  • 仅供参考,一些标点符号可能值得单独考虑。否则,“随身行李” 变成三个词,“USA” 也是如此,因此答案可能需要参数化允许使用的标点符号,而不是像 \S+ 这样的笼统正则表达式

标签: python list text counter python-textprocessing


【解决方案1】:

str.split() 不带任何参数在空白字符的运行中拆分:

>>> s = 'I am having a very nice day.'
>>> 
>>> len(s.split())
7

来自链接的文档:

如果 sep 未指定或为None,则应用不同的分割算法:连续的空格被视为单个分隔符,结果开头不包含空字符串如果字符串有前导或尾随空格,则结束。

【讨论】:

  • 这样做的一个(非常小的)缺点是您可以将标点符号组视为单词。例如,在'I am having a very nice day -- or at least I was.' 中,您会将-- 计为一个单词。 isalnum 可能会有所帮助,我猜,这取决于 OP 对“单词”的定义。
  • 这似乎比正则表达式更快
  • 当然更快,但也受到更多限制。
  • 不,计算标点符号:'apple & orange'.split() 给出['apple', '&', 'orange']
【解决方案2】:

你可以使用regex.findall():

import re
line = " I am having a very nice day."
count = len(re.findall(r'\w+', line))
print (count)

【讨论】:

  • 嗯,如果可以的话,我通常会避免使用正则表达式,但这似乎是一个很好的用例。
  • +1 使用re,确实比[i for i in string.split() if i.isalnum()]
  • 我宁愿依靠计数\S+来处理"It's 2.5 times faster"中的十进制数字之类的东西
  • 如果行是'inter-process communication',则计3个字
  • @GamesBrainiac:只是好奇。为什么你尽量避免使用正则表达式?
【解决方案3】:
s = "I     am having  a   very  nice  23!@$      day. "
sum([i.strip(string.punctuation).isalpha() for i in s.split()])

上面的语句将遍历每个文本块并删除标点符号,然后再验证该块是否真的是字母串。

【讨论】:

  • 1.使用i 作为非索引变量确实具有误导性; 2.你不需要创建一个列表,这只是在浪费内存。建议:sum(word.strip(string.punctuation).isalpha() for word in s.split())
【解决方案4】:

这是一个使用正则表达式的简单单词计数器。该脚本包含一个循环,您可以在完成后终止它。

#word counter using regex
import re
while True:
    string =raw_input("Enter the string: ")
    count = len(re.findall("[a-zA-Z_]+", string))
    if line == "Done": #command to terminate the loop
        break
    print (count)
print ("Terminated")

【讨论】:

  • 在 Python 3 中将 raw_input 更改为 input
【解决方案5】:
    def wordCount(mystring):  
        tempcount = 0  
        count = 1  

        try:  
            for character in mystring:  
                if character == " ":  
                    tempcount +=1  
                    if tempcount ==1:  
                        count +=1  

                    else:  
                        tempcount +=1
                 else:
                     tempcount=0

             return count  

         except Exception:  
             error = "Not a string"  
             return error  

    mystring = "I   am having   a    very nice 23!@$      day."           

    print(wordCount(mystring))  

输出为 8

【讨论】:

  • 正在寻找不使用内置函数(如剥离、拆分等)的解决方案。但此代码因前导/尾随空格而失败。
  • 这是最好的答案,因为它不使用任何标准库。
【解决方案6】:

好的,这是我的版本。我注意到您希望输出为7,这意味着您不想计算特殊字符和数字。所以这里是正则表达式模式:

re.findall("[a-zA-Z_]+", string)

[a-zA-Z_] 表示它将匹配 any 字符 beetwen a-z(小写)和 A-Z(大写)。


关于空间。如果您想删除所有多余的空格,只需执行以下操作:

string = string.rstrip().lstrip() # Remove all extra spaces at the start and at the end of the string
while "  " in string: # While  there are 2 spaces beetwen words in our string...
    string = string.replace("  ", " ") # ... replace them by one space!

【讨论】:

  • 不适用于像 ćęźńśü 这样的非英语字符
【解决方案7】:

用一个简单的循环来计算空格的出现次数怎么样!?

txt = "Just an example here move along" 
count = 1
for i in txt:
if i == " ":
   count += 1
print(count)

【讨论】:

  • 这里是另一种方法 print(input().count(' ') + 1)
  • 如果单词之间有多个空格,这将不起作用。
【解决方案8】:
import string 

sentence = "I     am having  a   very  nice  23!@$      day. "
# Remove all punctuations
sentence = sentence.translate(str.maketrans('', '', string.punctuation))
# Remove all numbers"
sentence = ''.join([word for word in sentence if not word.isdigit()])
count = 0;
for index in range(len(sentence)-1) :
    if sentence[index+1].isspace() and not sentence[index].isspace():
        count += 1 
print(count)

【讨论】:

    猜你喜欢
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多