如何让我的代码在python中检测字符串的结尾?
我正在尝试编写代码来拆分一个没有标点符号的句子。例如,如果用户输入如何让我的代码在python中检测字符串的结尾?,python,Python,我正在尝试编写代码来拆分一个没有标点符号的句子。例如,如果用户输入“你好,你好吗?”,我可以将句子拆分为[“你好”,“你好”,“你好”,“你”] userinput = str(raw_input("Enter your sentence: ")) def sentence_split(sentence): result = [] current_word = "" for letter in sentence: if letter.isalnum():
“你好,你好吗?”
,我可以将句子拆分为[“你好”,“你好”,“你好”,“你”]
userinput = str(raw_input("Enter your sentence: "))
def sentence_split(sentence):
result = []
current_word = ""
for letter in sentence:
if letter.isalnum():
current_word += letter
else: ## this is a symbol or punctuation, e.g. reach end of a word
if current_word:
result.append(current_word)
current_word = "" ## reinitialise for creating a new word
return result
print "Split of your sentence:", sentence_split(userinput)
到目前为止,我的代码是有效的,但是如果我在句子结尾没有标点符号,最后一个单词就不会出现在结果中,例如,如果输入是
“你好,你好吗”
,结果将是['Hello','how','are']
,我想这是因为没有标点符号告诉代码字符串结束了,有没有办法让程序检测到它是字符串的结尾?因此,即使输入是“你好,你好吗”
,结果仍然是[“你好”,“你好”,“你”和“你”]
,因为算法希望每个单词都以标点或空格结尾,所以可以在输入的末尾添加空格,以确保算法正确终止:
userinput = str(raw_input("Enter your sentence: ")) + " "
结果:
Enter your sentence: hello how are you
Split of your sentence: ['hello', 'how', 'are', 'you']
我自己没有试着调整你的算法,但我认为下面的方法应该达到你想要的效果
def sentence_split(sentence):
new_sentence = sentence[:]
for letter in sentence:
if not letter.isalnum():
new_sentence = new_sentence.replace(letter, ' ')
return new_sentence.split()
现在,随着它的运行:
运行文件(r'C:\Users\cat\test.py',wdir=r'C:\Users\cat')
[‘你好’、‘你好’、‘你’]
编辑:修复了新句子初始化的错误。您可以尝试以下方法:
def split_string(text, splitlist):
for sep in splitlist:
text = text.replace(sep, splitlist[0])
return filter(None, text.split(splitlist[0])) if splitlist else [text]
如果您将splitlist
设置为“!?,.”
或任何需要拆分的内容,这将首先用splitlist
中的第一个sep
替换每个标点,最后在第一个sep
上拆分整个句子,同时从返回的列表中删除空字符串(这就是过滤器(无,列表)
的作用)
或者您可以使用这个简单的正则表达式解决方案:
>>> s = "Hello, how are you?"
>>> re.findall(r'([A-Za-z]+)', s)
['Hello', 'how', 'are', 'you']
方法1:
为什么不直接使用re.split(“[我不喜欢的字符列表]”),s)
方法2:
清理字符串(删除不需要的字符):
然后执行
s.split(“”)
代码的问题是,除非您使用了非字母数字字符,否则您不会对结尾处的当前单词执行任何操作:
for letter in sentence:
if letter.isalnum():
current_word += letter
else:
if current_word:
result.append(current_word)
current_word = ""
return result
如果最后一个字母是另一个字符,它将被添加到current\u word
,但current\u word
将永远不会被追加到结果中。您可以通过在循环后复制追加逻辑来解决此问题:
for letter in sentence:
if letter.isalnum():
current_word += letter
else:
if current_word:
result.append(current_word)
current_word = ""
if current_word:
result.append(current_word)
return result
因此,现在,当循环后current\u word
为非空时,它也将被附加到结果中。如果最后一个字符是一些标点符号,current\u word
将再次为空,因此循环后if
的条件将不为真。最好用空格替换标点符号。否则,您将无法使用空格ge两个单词之间只用逗号分隔。我以前想过用这个方法,但这意味着我必须列出我能想到的所有标点符号,如果我能用str.isalnum()方法可能会更容易些?好的,我会调整以适应它。抱歉,但当我尝试你的代码时,结果是['hello','how','are','you']你确定你正在尝试上面的代码吗?对我来说很好。可能重复: