Question

So here is part of the code that selects a word in the "listb.txt" Its the second part of the line that gives me an issues. It can select a word based on the first character... but as soon as you say "and" the last character does it complain. example will be "mthr" and it must locate Mother . Num is the line that it finds the match in the file, /2 is because there is white space in between the words in the file, so it select the right one.

This should be all the info required... Does anyone have an idea? Thanks!

with open('listb.txt','r') as f:  
    x = 1
    for line in f:
        if x == num/2 and len(sms_word) <= len(line) < 2*(len(sms_word)) and sms_word[0] == line[0]:
            print line
            break
        x += 1                    
Was it helpful?

Solution

Firstly, you can simplify your code with enumerate:

for x, line in enumerate(f, 1):

Secondly, you can use startswith and endswith to test strings:

if (x == num / 2 and
    len(sms_word) <= len(line) < 2 * len(sms_word) and 
    line.startswith(sms_word[0]) and 
    line.endswith(sms_word[-1])):

Finally, lines from the file will have a newline character '\n' at the end, so strip() them first:

line = line.strip()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top