1

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)
2

2 Answers 2

1

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
1

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.

1
  • 1
    When looking for words, you usually don't want to pass an argument to str.split at all; without an argument, it splits on runs of whitespace, rather than single space characters only, and omits leading and trailing groups if the line begins or ends with whitespace. Commented Sep 25, 2015 at 3:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.