I want to have a method that return true when a string contain a certain word example i want the word musique and i want to check it with "musique.txt" i want to return true because "musique.txt" contain the word musique
def contains_word(contain, word):
print((' ' + word + ' ') in (' ' + contain + ' '))
return (' ' + word + ' ') in (' ' + contain + ' ')
contains_word('musique.txt', 'musique') # True
contains_word('musique1.txt', 'musique') # False
This would work:
def contains_word(contain, word):
with open(contain,'r') as f:
text = f.readlines()
for i in text:
temp = i.split()
for j in temp:
if word == j:
return True
return False
contains_word('musique.txt', 'musique')
Basically in this code, each and every word is matched against the provided word.
Related
I do reverse string and input is The quick brow fox
def reverse_word(word):
for i in word:
re = (i[::-1])
print('Reversed words ==> '+ re )
def main():
word = input('Enter a line : ').split()
reverse_word(word)
main()
but my result is
Reversed words ==> ehT
Reversed words ==> kciuq
Reversed words ==> worb
Reversed words ==> xof
I want result like:
Reversed words ==> ehT kciuq worb xof
you can use end in print method
def reverse_word(word):
print('Reversed words ==> ', end='')
for i in word:
re = (i[::-1])
print(re, end=' ' )
def main():
word = input('Enter a line : ').split()
reverse_word(word)
main()
Can try this one :
def reverse_word(word):
print("Reversed words ==>", end="")
for i in word:
re = (i[::-1])
print(" " + re, end="")
def main():
word = input('Enter a line : ').split()
reverse_word(word)
main()
In order to get a single line output , you can have a global string out = "" To which you will concatenate your resulting words.
out += " " + re
Inside the for loop
And this can be printed right after the end of the loop.
out = ""
def reverse_word(word):
for i in word:
re = (i[::-1])
out += " " + re
print("Reversed Words ==> " + out)
def main():
word = input('Enter a line : ').split()
reverse_word(word)
main()
def reverse_word(word):
res = ""
for i in word:
re = (i[::-1])
res += " "+re
return 'Reversed words ==>'+ res
word = input('Enter a line : ').split()
print(reverse_word(word))
Believe this would have desired effect.
Not really a question asked so no need to explain it further. Keep it simple!
When you say word it looks like this is really a collection of words, so words is probably a better name, and each of those should probably be word rather than i.
def reverse_words(words):
for word in words:
re = (word[::-1])
print('Reversed words ==> '+ re )
def main():
words = input('Enter a line : ').split()
reverse_words(words)
main()
Now, we can use a generator expression to generate the reversed word for each word.
(word[::-1] for word in words)
And let's join those with a space.
' '.join(word[::-1] for word in words)
And putting it into a function, using an f-string to print it:
def reverse_words(words):
print(f"Reversed words ==> {' '.join(word[::-1] for word in words)}")
Alternatively, we can use reversed.
def reverse_words(words):
print(f"Reversed words ==> {' '.join(''.join(reversed(word)) for word in words)}")
I want to merge 2 continuous empty string in a list and make it into 1 empty string. For example if it finds 4 continuous empty string then it should make 2 empty string out of it. In Python.
str_list = ['hi',' ',' ','hello',' ',' ',' ',' ','bye']
Desired Output : ['hi',' ','hello',' ',' ','bye']
Hope it works:
count=0
l2=[]
for i in str_list:
if i==' ':
count+=1
if (count%2)==0:
l2.append(' ')
count=0
else:
l2.append(i)
you can use a while loop:
i = 0
new_list = []
while i < len(str_list) - 1:
if str_list[i] == str_list[i + 1] == ' ':
new_list.append(' ')
i += 2
else:
new_list.append(str_list[i])
i += 1
# grab the last character if last 2 are not ' '
if i < len(str_list):
new_list.append(str_list[i])
print(new_list)
output:
['hi', ' ', 'hello', ' ', ' ', 'bye']
Try this
count = 0
new_list = []
for i in str_list:
if i == ' ' and count == 0:
count = count + 1
elif i == ' ' and count % 2 == 0:
for j in range(count // 2):
new_list.append(' ')
else:
new_list.append(i)
count = 0
If you don't want to remove all single space:
words = ["hi", " ", " ", "hello", " ", " ", " ", " ", "bye", " "]
rv = []
d = " "
skip = True
for i in words:
if i == d:
skip = not skip
if skip:
continue
rv.append(i)
print(rv)
Output:
['hi', ' ', 'hello', ' ', ' ', 'bye', ' ']
I am trying to pass words to a function that will be checked with words in a seperate file. It only passes the last word created from the first file and not each word. So I think how it should work is as soon as it creates a word it should pass that word to the function then check it and return the results, but I'm confused as to how. If the word matches a word in the second file it should print the word then a 0 or if it doesn't match a word then print 1.
import sys
argc = len(sys.argv)
cmdlength = argc - 1
if cmdlength != 2:
print ("Usage error, expected 2 args got " + str(cmdlength))
exit()
else:
word = ""
with open(sys.argv[1],"r") as fh:
while True:
ch=fh.read(1)
if not ch:
print(word)
print("End of file")
break
if ch == ' ':
print(word)
word = ''
else:
word += ch
def check_word(word):
count = 0
count2 = 0
with open(sys.argv[2],"r") as fh2:
lines = fh2.readlines()
for line in lines:
if word in line:
print(word , ": " , "0")
count += 1
else:
print(word, ": " , "1")
count += 1
check_word(word)
When you call the check_word function, you are doing it once after the while loop ends, for that reason only the last word is passed to the function. You should call the function after each word is armed, in your case, when ch == ' ':
if ch == ' ':
print(word)
check_word(word)
word = ''
import string
def main():
filename = input("Enter the name of a file to translate into Pig Latin: ")
vowels = ['a', 'e', 'i', 'o', 'u','A','E','I','O','U']
regFile = open((filename), 'r')
Output = open('Output.txt', 'w')
for line in regFile.readlines():
pigList = line.split()
t = translate(pigList, vowels)
w = write(t, Output)
regFile.close()
input ("Press ENTER to continue: ")
def translate(pigList, vowels):
PigList2 = []
for word in pigList:
if word[-1] in string.punctuation:
actual_word = word[:-1]
ending = word[-1]
else:
actual_word = word
ending = ""
if word[0] in vowels:
PigList2.append(actual_word + "-yay" + ending)
else:
PigList2.append(actual_word[1:] + "-" + actual_word[0] + "ay" + ending)
return PigList2
def write(pigList, Output):
print(" ".join(pigList))
main()
I believe this has fixed my errors. Thank you for the help. I know have the translator working correctly and translating all the lines at once instead of one line at a time.
You're almost there. I just used used the punctuation check to split up your word into the actual word and the punctuation and then append the '-' before the first letter rather than with the "ay".
def translate(pigList, vowels):
PigList2 = []
for word in pigList:
if word[-1] in string.punctuation:
actual_word = word[:-1]
ending = word[-1]
else:
actual_word = word
ending = ""
if word[0] in vowels:
PigList2.append(actual_word + "-yay" + ending)
else:
PigList2.append(actual_word[1:] + "-" + actual_word[0] + "ay" + ending)
return PigList2
I'm making a program that finds every word in a block of text and outputs each word and how many times the word was used.
My current code is here:
text = input("Please enter some text ")
terminator = len(text)
n = 0
word = ""
wordlist = []
while len(text) > 0:
if word != "":
wordlist.append(word)
text = text[n:]
word = ""
n = 0
for char in text:
if char != " ":
word = word + char
n = n + 1
else:
text = text[1:]
break
for item in wordlist:
print(item)
thanks :)
I'd do something like this:
import re
from collections import Counter
text = input("Please enter some text ")
text = re.sub(' +', ' ', text)
text = text.split(' ')
counter = Counter(text)
The line text = re.sub(' +', ' ', text) deals with cases where the user enters multiple consecutive spaces.