'Python script search a text file for specific letter in location
I'm trying to write a python script for a challenge that will locate the amount of times the letter 'e' appears as the third letter in a word. For example, the word "they". I was wondering if anyone had any tips or had a solution to what I'm trying to solve as I am not as experienced as most.
I found this code from "Python Script Search a Text File For A Word" that I was trying to use as a start, if anyone has ideas of what I could alter to meet the needs listed above, it would be greatly appreciated.
with open("/Users/djdees/Downloads/text.txt") as myfile:
words = [word for word in myfile.read().split(" ") if word.endswith("e") and len(word) > 3]
print("There are {} words ending with 'e' and longer than 3".format(len(words)))
Thanks For Everyones Help, DJ
Solution 1:[1]
You can try find to search index of letter in string as the code
with open("/Users/djdees/Downloads/text.txt") as myfile:
words = [word for word in myfile.read().split(" ") if word.find("e") == 2]
print("There are {} words with the letter 'e' appears as the third letter".format(len(words)))
Solution 2:[2]
Since we are checking if 'e' is the third letter of each word, we must check the 2nd index for every word in our file.
f = open("<Enter Your File's Name Here>", "r")
words = []
for line in f:
l = line.split(" ")
for word in l:
if len(word) > 3 and word[2] == 'e':
words.append(word)
print(words)
print("There are {} words ending with 'e' and longer than 3".format(len(words)))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | im_vutu |
| Solution 2 | Charlie |
