我如何计算句子中的单词?我正在使用Python。
例如,我可能有字符串:
string = "I am having a very nice 23!@$ day. "
那将是7个字。我在每个单词之后/之前以及涉及数字或符号时随机数量的空格都遇到了问题。
答案 0 :(得分:75)
str.split()
在空白字符的运行中分裂:
>>> s = 'I am having a very nice day.'
>>>
>>> len(s.split())
7
来自链接文档:
如果未指定 sep 或
None
,则应用不同的拆分算法:连续空格的运行被视为单个分隔符,结果将不包含空字符串如果字符串具有前导或尾随空格,则为开头或结尾。
答案 1 :(得分:46)
您可以使用regex.findall()
:
import re
line = " I am having a very nice day."
count = len(re.findall(r'\w+', line))
print (count)
答案 2 :(得分: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")
答案 3 :(得分:3)
s = "I am having a very nice 23!@$ day. "
sum([i.strip(string.punctuation).isalpha() for i in s.split()])
上面的语句将遍历每个文本块并删除标点符号,然后再验证该块是否真的是字母串。
答案 4 :(得分:2)
好的,这是我做这个的版本。我注意到您希望输出为7
,这意味着您不想计算特殊字符和数字。所以这里是正则表达式:
re.findall("[a-zA-Z_]+", string)
[a-zA-Z_]
表示匹配任何字符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!
答案 5 :(得分:2)
如何使用一个简单的循环来计算空格数的出现!!
txt = "Just an example here move along"
count = 1
for i in txt:
if i == " ":
count += 1
print(count)
答案 6 :(得分:1)
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
答案 7 :(得分:0)
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)