当在句号后拆分文本行时,如何指定不在标题“Dr.”之后拆分文本行?

2024-09-29 19:27:42 发布

您现在位置:Python中文网/ 问答频道 /正文

#!/usr/bin/python

#Opening the file
myFile=open ('Text File.txt', 'r')

#Printing the files original text first
for line in myFile.readlines():
print line

#Splitting the text
varLine = line
splitLine = varLine.split (". ") 

#Printing the edited text
print splitLine

#Closing the file
myFile.close()

当在Python程序中打开一个.txt文件时,我希望文本的输出格式像一个句子,也就是说,在显示句号之后,会生成一个新行。这就是我目前所取得的成就,但是我不知道如何防止这种情况的发生:句号不是用在句子的结尾,比如“Dr.”或“I.e.”等


Tags: thetexttxtbinusrlinemyfile句子
2条回答

如果控制输入,最好的方法是在一个句子的末尾使用两个空格(就像人们应该,IMHO),然后在'. '上使用split,这样就不会碰到Dr.or

如果你不控制输入。。。我不确定这是否真的是Python,但有一种方法可以做到:使用占位符来标识所有要保存句点的位置。下面,我假设'XYZ'从未出现在我的文本中。你可以随心所欲地把它变得复杂,越复杂越好(不太可能那样做)。在

sentence = "Hello, Dr. Brown.  Nice to meet you.  I'm Bob."
targets = ['Dr.', 'i.e.', 'etc.']
replacements = [t.replace('.', placeholder) for t in targets]
# replacements now looks like: ['DrXYZ', 'iXYZeXYZ', 'etcXYZ']
for i in range(len(targets)):
    sentence = sentence.replace(targets[i], replacements[i])
# sentence now looks like: "Hello, DrXYZ Brown.  Nice to meet you.  I'm Bob."
output = sentence.split('. ')
# output now looks like: ['Hello, DrXYZ Brown', ' Nice to meet you', " I'm Bob."]
output = [o.replace(placeholder, '.') for o in output]
print(output)
>>> ['Hello, Dr. Brown', ' Nice to meet you', " I'm Bob."]

使用in关键字进行检查。在

'.' in "Dr."
# True

'.' in "Bob"
# False

相关问题 更多 >

    热门问题