Maddy
Maddy

Reputation: 2060

Splitting individual sentence to list

I am asking on how to make individual lists. Not how to find a substring as marked duplicated for.

I have the following file

'Gentlemen do not read each others mail.' Henry Stinson
'The more corrupt the state, the more numerous the laws.' Tacitus
'The price of freedom is eternal vigilance.' Thomas Jefferson
'Few false ideas have more firmly gripped the minds of so many intelligent men than the one that, if they just tried, they could invent a cipher that no one could break.' David Kahn
'Who will watch the watchmen.' Juvenal
'Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin.' John Von Neumann
'They that give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety.' Benjamin Franklin
'And so it often happens that an apparently ingenious idea is in fact a weakness which the scientific cryptographer seizes on for his solution.' Herbert Yardley

I am trying to convert each sentence to a list so that when I search for the word say "Gentlemen" it should print me the entire sentence. I am able to get the lines to split but I am unable to convert them to individual list. I have tried a few things from the internet but nothing has helped so far.

here is what

def myFun(filename):
    file = open(filename, "r")
    c1 = [ line for line in file ]
    for i in c1:
        print(i)

Upvotes: 1

Views: 116

Answers (2)

Pedro
Pedro

Reputation: 385

Python strings have a split() method:

individual_words = 'This is my sentence.'.split()
print(len(individual_words)) # 4

Edit: As @ShadowRanger mentions below, running split() without an argument will take care of leading, trailing, and consecutive whitespace.

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 113930

you can use in to search a string or array, for example 7 in a_list or "I" in "where am I"

you can iterate directly over a file if you want

 for line in open("my_file.txt")

although to ensure it closes people recommend using a context manager

 with open("my_file.txt") as f:
      for line in f:

that should probably at least get you going in the right direction

if you want to search case insensitive you can simply use str.lower()

term.lower() in search_string.lower() #case insensitive

Upvotes: 1

Related Questions