Python: How to retrieve second word from the text - python

So the generator function generates a word char by char until "" and now I want the main function to call out generator function 100 times so that it would create a list words with 100 words. As I have it now it will call out the function 100x but only with one word. What should I do so that it would remember the words it has used already.
word = " "
def generator():
global word
with open("text.txt", "r") as file:
file.read(1)
for line in file:
for char in line:
if char != " ":
word += char
if char == " ":
return
def main():
words = []
for i in range(100):
generator()
words.append(word)
print(words)
if __name__ == '__main__':
main()

def word_generator():
word = ""
with open("text.txt", "r") as file:
file.read(1)
for line in file:
for char in line:
if char != " ":
word += char
if char == " ":
yield word
word = ""
that is now a generator
it is used like this
for word in word_generator():
print word
if you only want the first hundred you could do
for i,word in enumerate(word_generator()):
if i > 100:
break
print word
print "Last Word:",word

You can create a generator with yield, and manipulate the generator as you needed (say stop at 100).
def make_generator():
with open("text.txt", "r") as f:
for line in f:
for word in line.split():
yield word
def main():
words = []
generator = make_generator()
for i in range(100):
w = next(generator)
words.append(w)
print(words)
if __name__ == '__main__':
main()

Related

How to add a while true loop to count how many times a word was said in the text?

I'm trying to use dictionary and some loops to figure out how many times a word was written and if user types in "quit" then the program should stop. This is what I have so far:
import string
text = open('text.txt', 'r')
val = dict()
for i in text:
i = i.strip().lower().split(" ")
print(i)
This is one approach to the problem:
with open('text.txt', 'r') as file:
data = file.read()
data = data.replace('\n', ' ')
data = data.split(' ')
while True:
counter = 0
search_term = input('Word: ')
if search_term == 'quit':
break
for word in data:
if word.lower() == search_term.lower() or word.lower() == search_term.lower() + '.':
counter += 1
if counter == 0:
print('None found!')
else:
print(f'Number of "{search_term}": {counter}')

I've made an anagram function in python, I cannot figure out how to get the output to look like this: "Key": word1, word2, word3 etc

with open('words.txt', 'r') as read:
line = read.readlines()
key_list = []
def make_anagram_dict(line):
word_list = {}
for word in line:
word = word.lower()
key = ''.join(sorted(word))
if key in word_list and len(word) > 5:
word_list[key].append(word)
key_list.append(key)
else:
word_list[key] = [word]
return word_list
if __name__ == '__main__':
word_list = make_anagram_dict(line)
for words in word_list.values():
if len(words) > 1:
print('Words: {}'.format(', '.join(words)))
I.e I need it to look like this:
Key:
aeehrtw
Words:
weather
, whereat
, wreathe
I also have a problem where words in the .txt file are duplicated but one word starts with a capital, i.e Zipper and zipper. How can I have it so that it only uses one of the words?
To get the exact same output, you can try :
if __name__ == '__main__':
word_list = make_anagram_dict(line)
for key, words in word_list.items():
if len(words) > 1:
print('Key:')
print(key)
print()
print('Words:')
print('\n, '.join(words))

Replace a sequence of characters by another one

I have a sequence of characters '-------' and i want to replace each '-' in it by each letter in 'jaillir' in the correct range.
How do i do that ?
Here is my code
import random
with open ("lexique.txt", "r", encoding= "utf8") as a:
words = []
letters = []
tirets= []
for line in a:
ligne = line[:-1]
words.append(ligne)
choix = random.choice(words)
tiret = ('-'* len(choix))
print(tiret)
print(choix)
accompli = False
while not accompli:
lettre = input("Entrez une lettre du mot ")
for t in range(len(tiret)):
if lettre in choix:
tiret.replace(tiret[t], lettre[t])
print(tiret)
I think you need to fix your file reading code, even though it is not the question, as below:
with open('lexique.txt', r) as f:
text = f.read() # get file contents
Next to replace the ---- by a word, I am assuming that the dashes in your text will only ever be the same length as the word, so:
word = 'word' # any string e.g. word
dashes = '-' * len(word)
So now you can use python's string.replace method like so:
text = text.replace(dashes, word) # every time it finds the sequence of dashes it will be replaced by your word
With a for loop (gradual replacement):
word = 'word' # any word
length = len(word)
temp = ''
for i, letter in enumerate(text):
if letter == '-':
if i + len(tempword) < len(text):
characters = [True if l == '-' else False for l in text[i:i + len(tempword)]]
if not(False in characters):
new += tempword[0]
if len(tempword) > 1:
tempword = tempword[1:]
else:
tempword = word
else:
new += letter
else:
new += letter
print(new)

Appending Words to a list

I am trying to append the incorrect words to a list, however when I print the list outside of the function it is empty and when I print it inside the function it prints a list for each word. How do I get the list to print just one time with the incorrect words in it at the end of the program?
File 1:
this is my spell checker program
File 2: dis is my spll cheker program
So there are 3 incorrect words that should be added to the list
word_list = []
if cmdlength != 2:
print ("Usage error, expected 2 args got " + str(cmdlength))
exit()
else:
try:
f = open(sys.argv[1])
f.close()
except FileNotFoundError:
print("File does not exist")
exit()
try:
ff = open(sys.argv[2])
ff.close()
except FileNotFoundError:
print("File does not exist")
exit()
word = ""
with open(sys.argv[1],"r") as fh:
while True:
ch=fh.read(1)
if ch == " " or ch == "\n" or ch == ":" or ch == ".":
with open(sys.argv[2],"r") as fh2:
def check_word(word,fh2,word_list):
lines = fh2.readlines()
for line in lines:
x= re.search(word,line)
if x:
#correctwords
print(word + ": " + "0")
#count += 1
else:
#incorrect words
print(word, ": " , "1")
word_list.append(word)
#count2 += 1
check_word(word,fh2,word_list)
word = ''
else:
word += ch
if not ch:
print(word)
print("End of file")
print(word_list)
break
The function is missing a return statement to return word_list.
This should work
...
def check_word(word,fh2,word_list):
lines = fh2.readlines()
for line in lines:
...
word_list.append(word)
#count2 += 1
return word_list
word_list = check_word(word,fh2,word_list)

TypeError: 'str' object is not callable (python 2)

program to check if word starts & ends with same letter
def match_letter():
count = 0
for word in words:
if len(word) >=2 and word[0] == word[-1]:
count = count + 1
return count
def main():
words = []
words_list = raw_input('Enter Words: ')
words_list = words_list().split()
for word in words_list:
words.append(word)
count = match_letter()
print 'letter matched %d ' %count
if __name__ == '__main__':
main()
this is my python code, giving an error
Traceback (most recent call last):
File "D:\Programming\Python\Python 2.7\same_letter.py", line 21, in <module>
main()
File "D:\Programming\Python\Python 2.7\same_letter.py", line 13, in main
words_list = words_list().split()
TypeError: 'str' object is not callable
i am very thankful if anyone can help me..
This line has an extra parentheses
words_list = words_list().split()
It could just be
words_list = words_list.split()
In fact, you have a number of extraneous steps, your code block
words = []
words_list = raw_input('Enter Words: ')
words_list = words_list().split()
for word in words_list:
words.append(word)
Could be reduced to:
words = raw_input('Enter Words: ').split()
And if I understand your question, I would solve this using slicing
def same_back_and_front(s):
return s[0] == s[-1] # first letter equals last letter
>>> words = ['hello', 'test', 'yay', 'nope']
>>> [word for word in words if same_back_and_front(word)]
['test', 'yay']
Thanx Cyber.. It works for me.
this code works for me exactly as i want
def match_letter(words):
count = 0
for word in words:
if len(word) >=2 and word[0] == word[-1]:
count = count + 1
return count
def main():
words = raw_input('Enter Words: ').split()
count = match_letter(words)
print 'letter matched %d ' %count
if __name__ == '__main__':
main()

Categories