python:Move a specific word at the end of a string - python

i learn python and i do a discord bot. I have some difficulties to print the element after "anivia". i cant say if there is "anivia" in the 'texte' and i can count him but i don't know how to print the element after "anivia", if someone can help me please :)
#bot.command()
async def counter(ctx, *champion):
champion = " ".join(champion)
url = "https://u.gg/lol/champions/"
counter = "/counter"
uurl = url + champion + counter
await ctx.send(uurl)
import urllib.request
with urllib.request.urlopen(uurl) as response:
texte = response.read()
if ("anivia" in str(texte)):
print("Le mot existe !")
else:
print("Le mot n'existe pas!")
test = str(texte)
z = test.count('anivia')
print(z)
I can count 9 "anivia" with z and i want to print the next element after all the anivia (example: " hello i m anivia and i like anivia test": and, test).
Thanks for your help :)

If you're familiar with regular expressions (regex), this becomes very simple:
import re
# This pattern will capture the first word that comes after "anivia"
pattern = r'anivia (\w+)'
# Using this string as our example input
example_string = "anivia first anivia second and finally anivia third"
results = re.findall(pattern, example_string)
print(results) # Output: ['first', 'second', 'third']

Here is an approach that uses an auxiliary variable to mark when the next word needs to be printed.
test_string = "Hello, I am anivia on mid or anivia jungle"
do_print = False
splitted = test_string.split()
for word in splitted:
if do_print:
do_print = False
print(word)
if word == "anivia":
do_print = True
Output:
on
jungle

yeah, the those solution works with strings (i tried too with regex) but
do_print = False
splitted = test_string.split()
for word in splitted:
# print(word)
if do_print:
do_print = False
if word == "anivia":
do_print = True
test_string = str(texte)
do_print = False
splitted = test_string.split()
for word in splitted:
# print(word)
if do_print:
do_print = False
# print(word)
if word == "champion_id":
do_print = True``
on the first case i have the ("on" and the "jungle") but with my str(texte), that's doesn't fonction :S.
If someone knows why, the 2 test_strings are "strings"
^^ ty for your answers :)

Related

How do you replace text with .replace and print the new sentence

I'm trying to make a mad libs program and am having trouble with .replace and don't know why its not working, I'm pretty new to coding and don't know too much.
import random
def main():
libs = input('Hello! Would you like to play MadLibs? Enter y or n: ')
libs = libs.lower()
while libs == 'y':
paragraph = madLibs()
para = replace(paragraph)
print(para)
libs = input('Would you like to play again? ')
libs = libs.lower()
if libs == 'n':
exit()
if libs != 'y' or 'n':
print('That is not a valid option')
main()
def madLibs():
madLibs = {1 : 'Today I went to the zoo. I saw a(n) ADJECTIVE jumping up and down in its tree',
2 : "I walk through the jungle. I take out my ADJECTIVE canteen.",
3 : 'The day I saw the Monkey King VERB was one of the most interesting days of the year.'}
randNum = random.randint(1, 3)
chosenLib = madLibs.get(randNum, 'Entry not found')
return chosenLib
def replace(para):
for line in para:
if 'ADJECTIVE' in para:
adj = str(input('Type an Adjective: '))
para.replace('ADJECTIVE', adj)
elif 'NOUN' in para:
noun = str(input('Type a Noun: '))
para.replace('NOUN', noun)
elif 'VERB' in para:
verb = str(input('Type a Verb: '))
para.replace('VERB', verb)
elif 'ADVERB' in para:
adv = str(input('Type an Adverb: '))
para.replace('ADVERB', adv)
return para
main()
The problem is in the replace function. Why is it not replacing?
The REPL can help elucidate what is happening:
>>> s = "ABC"
>>> t = s.replace("A","Alpha")
>>> s
'ABC'
>>> t
'AlphaBC'
>>>
Since you are just calling replace() and not saving the result, the original string is being returned.
That said, I think you also have a problem here:
def replace(para):
for line in para:
It's not made clear in your code, but I think you're actually passing a single string into replace, which means your for line in para is actually iterating through each character in the single line you pass in. Therefore, you will never match a full word. You can (dis)prove this by printing out what is coming into the function.
Using a simplified version of what you've written, we can see this in the REPL as well:
>>> def madLibs():
... return "Test ADJECTIVE string"
...
>>> def replace(para):
... for line in para:
... print(f"This is the line: {line}")
...
>>> paragraph = madLibs()
>>> replace(paragraph)
This is the line: T
This is the line: e
This is the line: s
This is the line: t
This is the line:
This is the line: A
This is the line: D
This is the line: J
This is the line: E
This is the line: C
This is the line: T
This is the line: I
This is the line: V
This is the line: E
This is the line:
This is the line: s
This is the line: t
This is the line: r
This is the line: i
This is the line: n
This is the line: g
Your code only replaces one items then returns. You want to keep replacing stuff until there's nothing to replace, and there's no point in doing things line by line. Also, input returns a string, so there is no point in passing it to str.
def replace(para):
while True:
if 'ADJECTIVE' in para:
adj = input('Type an Adjective: ')
para = para.replace('ADJECTIVE', adj)
continue
elif 'NOUN' in para:
noun = input('Type a Noun: ')
para = para.replace('NOUN', noun)
continue
elif 'VERB' in para:
verb = input('Type a Verb: ')
para = para.replace('VERB', verb)
continue
elif 'ADVERB' in para:
adv = input('Type an Adverb: ')
para = para.replace('ADVERB', adv)
continue
return para
There are better ways to do this by using a dict to avoid the multiple ifs. Here's an example that builds the prompt from the part of speech being requested.
def replace(para):
match = True
while match:
match = False
for part in ('ADJECTIVE','NOUN','VERB','ADVERB'):
if part in para:
rep = input('Type a ' + part.title() + ': ')
para = para.replace(part, rep, 1)
match = True
return para
Note that I added "1" to the replace call. That will limit it to replacing one thing at a time. Otherwise, if you had two VERBs in the paragraph, it would replace ALL occurrences of "VERB" with whatever was typed.
Looks like you have the return inside the loop in replace, so you're returning after only replacing one thing, skipping the rest.
Try bringing the return down an indentation level so you can go through all the lines before returning.

I made a program that checks if a word in in a file, need some advice

I want to print if the word appears, as well as how many times the word appears in the file. I can't get it to say anything other than this word appears 1 or 0 times in the file.
This problem occurs on line 26, print("It appears " + str(wordcount[word]) + " times")
specifically str(wordcount[word]). This probably simple question, but this is my first week of python so if anyone has an idea please share. Thanks!
I've tried putting wordcount[word], word_counter.__getitem__(wordcount[word]), and word_counter.__getitem__(wordcount)
import collections
file = open(r"C:\Users\Patrick Wu\Documents\1wordfreqtest.txt", "r")
if file.mode == "r":
contents = file.read()
word = input("Word to check for :")
wordcount = {}
"""this below is to remove difference between upper and lower cases as
well as punctuation"""
for word in contents.lower().split():
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace("\"","")
word = word.replace("!","")
word = word.replace("“","")
word = word.replace("‘","")
word = word.replace("*","")
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
word_counter = collections.Counter(wordcount)
if word in str(contents):
print("This word is in the file :)")
print("It appears " + str(wordcount[word]) + " times")
else:
print("This word isn't in the file")
The variable word is overwritten in the local scope, by the loop. So your input word is overwritten by the loop and you end up checking the count of the last word of the input file. Change the input word to be a different variable name than the word you're iterating through in the file.
You have a scoping problem, by using the same name "word" both in the input and in the for-loop.
I would suggest doing something like this:
word = input("Word to check for :")
with open('your_file.txt') as f:
raw = f.read()
num_appearences = raw.count(word)
print(f"The word {word} appears {num_appearences} times in the file")
You can use this code:
import collections
file = open("wordfreqtest.txt", "r")
if file.mode == "r":
contents = file.read().lower()
word = input("Word to check for :").lower()
times = 0
finish = 0
while finish==0:
if word in contents:
contents = contents[contents.find(word) + len(word):]
times += 1
else:
break
if times > 0:
print("This word is in the file :)")
print("It appears " + str(times) + " times")
else:
print("This word isn't in the file")

Python - Removing paragraph breaks in input

So I have written a program (however ugly) that counts the number of words and the instances of each unique word in a given input.
My problem is that I want to use it for song lyrics, but most lyric sets come with multiple paragraph breaks.
My question is: how can I take a user input of lyrics with paragraph breaks and reduce the input down to a single string?
This is my code so far:
Song = {}
lines = []
while True:
line = input("")
if line:
lines.append(line)
else:
break
string = '\n'.join(lines)
def string_cleaner(string):
string = string.lower()
newString = ''
validLetters = " abcdefghijklmnopqrstuvwxyz"
newString = ''.join([char for char in string if char in validLetters])
return newString
def song_splitter(string):
string = string_cleaner(string)
words = string.split()
for word in words:
if word in Song:
Song[word] += 1
else:
Song[word] = 1
Expected input:
Well, my heart went "boom"
When I crossed that room
And I held her hand in mine
Whoah, we danced through the night
And we held each other tight
And before too long I fell in love with her
Now I'll never dance with another
(Whooh)
Since I saw her standing there
Oh since I saw her standing there
Oh since I saw her standing there
Desired output:
This song has 328 words.
39 of which are unique.
This song is 11% unique words.
('i', 6)
('her', 4)
('standing', 3)
.... etc
The following example code extracts all the words (English alphabet only) from every line and process them (counts the number of words, and retrieve instances of each unique word).
import re
MESSAGE = 'Please input a new line: '
TEST_LINE = '''
Well, my heart went "boom"
When I crossed that room
And I held her hand in mine
Whoah, we danced through the night
And we held each other tight
And before too long I fell in love with her
Now I'll never dance with another
(Whooh)
Since I saw her standing there
Oh since I saw her standing there well well
Oh since I saw her standing there
'''
prog = re.compile(r'\w+')
class UniqueWordCounter():
def __init__(self):
self.data = {}
def add(self, word):
if word:
count = self.data.get(word)
if count:
count += 1
else:
count = 1
self.data[word] = count
# instances of each unique word
set_of_words = UniqueWordCounter()
# counts the number of words
count_of_words = 0
def handle_line(line):
line = line.lower()
words = map(lambda mo: mo.group(0), prog.finditer(line))
for word in words:
global count_of_words
count_of_words += 1
set_of_words.add(word)
def run():
line = input(MESSAGE)
if not line:
line = TEST_LINE
while line:
'''
Loop continues as long as `line` is not empty
'''
handle_line(line)
line = input(MESSAGE)
count_of_unique_words = len(set_of_words.data.keys())
unique_percentage = count_of_unique_words / count_of_words
print('-------------------------')
print('This song has {} words.'.format(count_of_words))
print('{} of which are unique.'.format(count_of_unique_words))
print('This song is {:.2%} unique words.'.format(unique_percentage))
items = sorted(set_of_words.data.items(), key = lambda tup: tup[1], reverse=True)
items = ["('{}', {})".format(k, v) for k, v in items]
print('\n'.join(items[:3]))
print('...')
run()
If you want to handle lyrics in other languages, you should check out this link.

Python how to check if word is in list and in input?

I'm trying to get my program to go through an input sentence (e.g. "hello there!")
and see if any of the words in the input are in a list.
here is the code so far:
def findWholeWord(w):
return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search
i.upper() #i is the inputted variable as a string
WordsDocument = open('WordsDocument.txt').readlines()
for words in WordsDocument:
WordsList.append(words)
for word in i:
if findWholeWord(word) in WordsList:
print("Word Match")
Can someone help me develop a better solution / fix this so it works?
import re
def findWholeWord(w): # input string w
match_list = [] # list containing matched words
input_list = w.split(" ")
file = open('WordsDocument.txt', 'r')
text = file.read().lower()
file.close()
text = re.sub('[^a-z\ \']+', " ", text)
words_list = list(text.split())
for word in input_list:
if word in words_list:
print("Word Found: " + str(word))
match_list.append(word)
return match_list

Program that searches for words that use certain letters

I'm designing a program that looks through a list of words, and counts how many words only have the letters p, y, t, h, o and n in them.
So far, my code is:
def find_python(string, python):
"""searches for the letters 'python' in the word."""
for eachLetter in python:
if eachLetter not in string:
return False
return True
def main():
python = 'python'
how_many = 0
try:
fin = open('words.txt')#open the file
except:
print("No, no, file no here") #if file is not found
for eachLine in fin:
string = eachLine
find_python(string, python)
if find_python(string, python) == True:
how_many = how_many + 1#increment count if word found
print how_many#print out count
fin.close()#close the file
if __name__ == '__main__':
main()
However, my code is returning the incorrect number of words, for example, it will return the word 'xylophonist' if I put in the print statement for it because it has the letters python in it. What should I do so it will reject any word that has forbidden letters?
Correct your test function:
def find_python(string, python):
"""searches for the letters 'python' in the word.
return True, if string contains only letters from python.
"""
for eachLetter in string:
if eachLetter not in python:
return False
return True
Welcome to regular expressions:
import re
line = "hello python said the xylophonist in the ythoonp"
words = re.findall(r'\b[python]+\b',line)
print words
returns
['python', 'ythoonp']
If what you want is to find how many times the actual word python appears, then you should issue a re.findall(r'\bpython\b')
If you don't want to go this route, I suggest you return false if any of the letters of the string is NOT p,y,t,h,o or n.
from os import listdir
def diagy(letters,li):
return sum( any(c in letters for c in word) for word in li )
def main():
dir_search = 'the_dir_in_which\\to_find\\the_file\\'
filename = 'words.txt'
if filename in listdir(dir_search):
with open(dir_search + 'words.txt',) as f:
li = f.read().split()
for what in ('pythona','pyth','py','ame'):
print '%s %d' % (what, diagy(what,li))
else:
print("No, no, filename %r is not in %s" % (filename,dir_search))
if __name__ == '__main__':
main()

Categories

Resources