Emmanu Emmanu - 7 months ago 20
Python Question

Print sentences from text file that starts and ends with particular words or character?

How to find sentences in text file that starts and ends with particular words for example sentences that starts with 'The' and ends with 'u'.I have tried

def main():
f=open('D:\\file.txt')
print 'The lines that starts with The and Ends with u'
for line in f:
for j in line.split('.'):
if j[0]=='T' and j[1]=='h' and j[2]=='e' and j[3]==' ' and j[-1]=='u':
print j
if __name__ == '__main__':main()


Instead of character comparison can we do this using word comparison?

Answer

You could use startswith and endswith to do the comparison with strings:

print 'The lines that starts with The and Ends with u'

with open('test.txt') as f:
    for line in f:
        line = line.strip()
        if line.startswith('The') and line.endswith('u'):
            print line
Comments