【问题标题】:Python - Count and split/strip words in strings [duplicate]Python - 计算和拆分/剥离字符串中的单词[重复]
【发布时间】:2018-09-28 06:49:57
【问题描述】:

下面的 python 代码将“resting-place”读作一个单词。
修改后的列表显示为:['This', 'is', 'my', 'resting-place.']
我希望它显示为:['This', 'is', 'my', 'resting', 'place']

因此,总共给了我 5 个单词,而不是修改后的列表中的 4 个单词。

original = 'This is my resting-place.'
modified = original.split()
print(modified)

numWords = 0
for word in modified:
    numWords += 1

print ('Total words are:', numWords)

输出是:

Total words are: 4

我希望输出有 5 个单词。

【问题讨论】:

  • 如果您想要的话,也可以在'-' 拆分...numWords = sum(len(word.split('-')) for word in modified)
  • @mij contd from above comment: 所以,我想删除“-”并将 resting-place 读为两个词,而不是一个。
  • 是的,您的字符串中的这些单词之间没有空格,但这无关紧要。该问题的最佳答案从字符串中删除空格和标点符号以仅给出单词,无论每个单词之间有多少。在您的字符串上使用该问题的答案,re.findall(r"[\w']+", original) 给出['This', 'is', 'my', 'resting', 'place']

标签: python split counting strip word-count


【解决方案1】:

代码如下:

s='This is my resting-place.'
len(s.split(" "))

4

【讨论】:

  • 我想把 resting-place 读成两个词。因此,计数应该是 5 个单词而不是 4 个。
【解决方案2】:

-计算句子中的单词数拆分为两个单词:

>>> original = 'This is my resting-place.'
>>> sum(map(original.strip().count, [' ','-'])) + 1
5

【讨论】:

  • 这不会给出准确的答案,因为您每次都添加一个。如果字符串中有更多连字符,则答案将不正确。此解决方案不适用于具有多个连字符对的字符串可能性。
  • @SamVitare,请举一个失败场景的例子。
  • 嗨,我为我的错误道歉,当我改变原来的 = 'This is my resting-place peter-pan.',我不知道为什么我得到 6 而不是 7 . 但是我又跑进去了,我得到了正确的答案。我一定是打错了什么。
  • 对于这个输入,我的代码输出 7(有 7 个字)。
  • 不用担心。一年后您回来将答案标记为已接受实际上很好。所以很感谢你。 :)
【解决方案3】:

我想你会在这篇文章中找到你想要的,在这里你可以找到如何创建一个函数,你可以在其中传递多个参数来分割一个字符串,在你的情况下你将能够分割那个额外的字符

http://code.activestate.com/recipes/577616-split-strings-w-multiple-separators/

这是最终结果的示例

>>> s = 'thing1,thing2/thing3-thing4'
>>> tsplit(s, (',', '/', '-'))
>>> ['thing1', 'thing2', 'thing3', 'thing4']

【讨论】:

    【解决方案4】:

    你可以使用正则表达式:

    import re
    original = 'This is my resting-place.'
    print(re.split("\s+|-", original))
    

    输出:

    ['This', 'is', 'my', 'resting', 'place.']
    

    【讨论】:

    • 寻求优雅、有效的解决方案!
    • 你确实改变了你的解决方案以匹配被骗者的......
    • 为什么不只是re.split('\W+', original)?然后过滤None
    • “\s+|-”和“\W+”有什么区别
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 2019-11-01
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多