Search code examples
pythonlist-comprehensioncase-insensitive

how to find string in text file by compare it with user input using python?


I have Code that read files and compare it with user input (case-insensitive).

I used the list-comprehension in order to loop through the content and compare with user-input.

The problem is that the list comprehension return an empty list, although the entered word exist. Example:

user-input :Bruce

Excpected Result : Bruce, Bruce (because it exist in the list).

result = empty list

code:

user_input = self.lineEditSearch.text()
print(user_input)
textString = self.ReadingFileContent(Item)
listText = list(textString.splitlines())
print(listText)

#self.varStr = [c for c in textString if c.islower() or c.isupper() or c.capitalize()]            
self.varStr = [item for item in textString if user_input.lower() in item.lower()]            

print(self.varStr)

output of print(listText):

['v01 ', '', ' ', 'Bruce Demaugé', '-', 'Bost ', '', ' ', 'http://bdemauge.free.fr', ' ', 'Les hiboux', ' ', 'Charles Baudelaire', ' ', 'Cycle 3', ' ', '*', ' ', 'POÉSIE', ' ', 'Sous les ifs noirs qui les abritent', ' ', '', ' ', '', ' ', '', ' ', ' ', 'Sans remuer ils se tiendront', ' ', '', ' ', '', ' ', '', ' ', ' ', 'Leur attitude au sage enseigne', ' ', "Qu'il faut en ce monde qu'il craigne", ' ', 'Le tumulte et le mouvement', ' ', ';', ' ', ' ', "L'homme ivre d'une ombre qui passe", ' ', '', ' ', "D'avoir voulu changer de place. ", ' ', ' ', ' ', 'Les Fleurs du Mal', ' ', '1857', ' ', 'Charles Pierre Baudelaire (1821 ', '', ' ', '1867) est un poète français.', ' ', ' ', '', '', 'les et un voyage forcé aux Indes, il est revenu à Paris et a mené une vie dissolue. Un de ses recueils de poèmes, ', 'Les Fleurs du Mal', '', '', '', 'mort à Paris, en 1867, après avoir cumulé pendant un an les problèmes de santé.', ' ', '<br/>v01 ', '', ' ', 'Bruce Demaugé', '-', 'Bost ', '', ' ', 'http://bdemauge.free.fr', ' ', '', ' ', 'Charles Baudelaire', ' ', 'Cycle 3', ' ', '**', ' ', 'POÉSIE', ' ', '', ' ', 'Prennent des albatros, vastes oiseaux des mers,', ' ']

Solution

  • It appears to me that within your list comprehension you just have one minor issue! Instead of:

    item for item in textString
    

    within your list comprehension, I would suggest:

    item for item in listText
    

    as currently you are iterating through each char of the whole text, rather than each element in the list of the split document.