Python 如何计算分号前后的单词数
例如: -----“贝茜说我做了什么?”我问道。Python 如何计算分号前后的单词数,python,Python,例如: -----“贝茜说我做了什么?”我问道。 -----“简,我不喜欢吹毛求疵的人或发问的人;此外,一个孩子以那种方式对待她的长辈确实有点令人生畏。 -----坐在某个地方,在你能愉快地说话之前,保持沉默。” 每个句子最多有一个分号。我的问题是有些句子不包含分号,所以rightWord=Word[1]。split()将超出范围。怎么做?首先,用分号作为分隔符拆分字符串 拆分字符串将是一个列表。现在检查长度。如果长度为1,则表示字符串没有分号。如果长度为2,则它有一个分号。(我不知道你是否有
-----“简,我不喜欢吹毛求疵的人或发问的人;此外,一个孩子以那种方式对待她的长辈确实有点令人生畏。
-----坐在某个地方,在你能愉快地说话之前,保持沉默。”
每个句子最多有一个分号。我的问题是有些句子不包含分号,所以rightWord=Word[1]。split()将超出范围。怎么做?首先,用分号作为分隔符拆分字符串 拆分字符串将是一个列表。现在检查长度。如果长度为1,则表示字符串没有分号。如果长度为2,则它有一个分号。(我不知道你是否有一个场景,其中会有多个分号,因为问题中没有提到) 检查长度后,您可以使用拆分来计算单词数 完整示例代码:
countLeft=0
countRight=0
for line in open("jane_eyre_sentences.txt"):
line_strip = line.rstrip();
splitWord = line_strip.split(";");
leftWord=splitWord[0].split();
rightWord=splitWord[1].split();
for word in leftWord:
countLeft+=1
for word in rightWord:
countRight+=1
如果某个字符串为*“这是一个带;分号的字符串”,则输出为:
split_string = some_string.split(";")
if not split_string:
left_words = 0
right_words = 0
elif len(split_string) > 1:
left_words = len(split_string[0].split())
right_words = len(split_string[1].split())
else:
left_words = len(split_string[0].split())
right_words = 0
print "Left words: ", left_words
print "Right words: ", right_words
Left words: 6
Right words: 1
如果某个字符串是*“这是一个没有分号的字符串”,则输出为:
split_string = some_string.split(";")
if not split_string:
left_words = 0
right_words = 0
elif len(split_string) > 1:
left_words = len(split_string[0].split())
right_words = len(split_string[1].split())
else:
left_words = len(split_string[0].split())
right_words = 0
print "Left words: ", left_words
print "Right words: ", right_words
Left words: 6
Right words: 1
干杯。发布你的代码,而不是你的代码截图。你还可以分享一些示例输入数据吗?似乎你想得到分号之间的句子长度?是简,我不喜欢吹毛求疵者或发问者;此外,一个孩子以这种方式对待她的长辈确实是一件令人生畏的事情。一句话?是的,那是一句话非常感谢你,丹尼。