Python - 在字符串中计算和拆分单词

时间:2018-04-18 06:35:05

标签: python split counting words word-count

下面的python代码显示了“休息地点”'一个字。
修改后的列表显示为:['此',','我的','休息地点。']
我希望它显示为:['此',','我的','休息','地点&# 39]

因此,在修改后的列表中总共给出了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)

4 个答案:

答案 0 :(得分:3)

代码如下:

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

4

答案 1 :(得分:1)

您可以使用正则表达式:

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

<强>输出:

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

答案 2 :(得分:1)

要计算-句子中单词的数量,将其分为两个单词,不用分割:

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

答案 3 :(得分:0)

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

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

这是最终结果的一个例子

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