0
#!/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()

When opening a .txt file in a Python program, I want the output of the text to be formatted like a sentence i.e. after a full stop is shown a new line is generated. That is what I have achieved so far, however I do not know how to prevent this happening when full stops are used not at the end of a sentence such as with things like 'Dr.', or 'i.e.' etc.

Scott
  • 1
  • 1
  • 3

2 Answers2

0

Best way, if you control the input, is to use two spaces at the end of a sentence (like people should, IMHO), then use split on '. ' so you don't touch the Dr. or i.e.

If you don't control the input... I'm not sure this is really Pythonic, but here's one way you could do it: use a placeholder to identify all locations where you want to save the period. Below, I assume 'XYZ' never shows up in my text. You can make it as complex as you like, and it will be better the more complex it is (less likely to run into it that way).

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."]
BlivetWidget
  • 10,543
  • 1
  • 14
  • 23
-2

Use the in keyword to check.

'.' in "Dr."
# True

'.' in "Bob"
# False
coder guy
  • 531
  • 1
  • 3
  • 12