例如,我有这句话:
hello. my name is Jess. what is your name?
我希望将其更改为:
Hello. My name is Jess. What is your name?
我提出了这个代码,但我将一切连接在一起有一个问题
def main():
name = input('Enter your sentence: ')
name = name.split('. ')
for item in name:
print (item[0].upper() + item[1:], end='. ')
当我输入句子时,它将返回:
Hello. My name is Jess. What is your name?.
如何阻止标点符号出现在句子末尾? 另外,如果我在中间有一个问题,例如:
hi. what is your name? my name is Jess.
答案 0 :(得分:1)
您可以按照相同的步骤构建字符串,并显示字符串,但最后两个值除外(您还需要删除最后一个空格):
def main():
result = ""
name = input('Enter your sentence: ')
name = name.split('. ')
for item in name:
result += item[0].upper() + item[1:] + '. '
print result[:-2]
答案 1 :(得分:1)
作为替代方案(也可能是过度复杂化),您可以使用nltk
的{{3}}。依靠Sentence Segmentation:
>>> import nltk.data
>>>
>>> sent_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
>>>
>>> text = "hello. my name is Jess. what is your name?"
>>>
>>> sentences = sent_tokenizer.tokenize(text)
>>> sentences = [sent.capitalize() for sent in sentences]
>>> print(' '.join(sentences))
Hello. My name is jess. What is your name?
为什么它不像.
分割字符串那么简单?一般来说,.
的问题在于它不仅仅是一个句子分隔符。它也可以是句子中缩写或标记缩写的一部分(也可以考虑所有Mr.
,Mrs.
,Dr.
等等:
句子分割很困难,因为句号用于标记 缩写,和一些句号同时标记缩写 并且终止一个句子,就像美国的缩写词一样。
答案 2 :(得分:0)
我是否可以忽视显而易见的情况,还是可以恰到好处地剥离?
即在输出字符串之前:
finalstring = string.rstrip('.')
答案 3 :(得分:0)
我已经针对类似问题编写了解决方案,您可以在此处阅读以下代码的工作原理:https://stackoverflow.com/a/48688182/5265414
original_data = raw_input("Enter text: ")
list = original_data.split(".")
if original_data.endswith('.'):
list.remove('')
for w in list:
stripper= w.strip().capitalize() +"."
print stripper,
答案 4 :(得分:0)
这是更好的解决方案
x = "hello. my name is Jess. what is your name?"
print( '. '.join(map(lambda s: s.strip().capitalize(), x.split('.'))))
output:
Hello. My name is jess. What is your name?