-1

I don't even know how to go about scanning a file (line by line) for a word (with 3 letters) in a logical way, that will let me set a suggested (3 letter) word as a variable (or maybe something better for me to call upon later?).

With that variable, I would first have the program verify with me that it is a 3 letter word.

I am a beginner in python, so I am not very efficient with my coding. I made a python file that is 150+ lines of code that doesn't work. If you would like me to add it just comment and I will add the whole file to this page. I have already looked at the link [Find 3 letter words but it didn't help me with what I am trying to accomplish.

Ethan McRae
  • 124
  • 2
  • 13
  • 1
    What's wrong with the link? How doesn't it help you? Just read your file line by line and extract 3 letter words and put em in a list. – cs95 Aug 14 '17 at 03:08
  • 1
    `words = [word for line in string.split() if len(word) == 3]` folllow this after you read the files and iterate through `lines`. Its the non `regex` approach as suggested in the link you have mentioned @Ethan – ShivaGaire Aug 14 '17 at 03:43

1 Answers1

1

This may help:

with open("filename.txt") as f:
lines = f.readlines()
for line in lines:
    words = [word for word in line.split() if len(word)==3 ]
print(words)
ShivaGaire
  • 2,283
  • 1
  • 20
  • 31
  • How would I then take each word from the new list I have and export them to a new file (each word has its own line). – Ethan McRae Aug 14 '17 at 04:55
  • @EthanMcRae So, you have to write the word into the corresponding line as original file? – ShivaGaire Aug 14 '17 at 05:26
  • No, I would want to write each word from 'words' to a file called 'words3.txt' – Ethan McRae Aug 14 '17 at 06:03
  • 1
    for that First open the file `words3.txt` `with open("words3.txt",'w') as w` and then use `for` loop to write like this: `for item in words:` `w.write("{}\n".format(item))` Sorry for the wrong indentation. Above approach will write `words` item in new line in `words3.txt` Hope this helps. – ShivaGaire Aug 14 '17 at 06:07
  • 1
    Yup, that did it. Thanks for your continuous help! – Ethan McRae Aug 14 '17 at 07:51