I have a piece of code that will search through a transcript of a call between a marketer and a customer. The code scans through the transcript line by line searching for a phrase specified in an external txt file, if it finds a match, it prints the entire line the match is on, followed by the next line, which is the response.
I've developed a bit of code that will identify if 'yes' has been said to one question, which will lead to more follow up questions, however, I cannot get it to loop through the rest of the script searching for these follow up questions after the line?
Could anyone give me a hand?
I have the following code:
with open ('/Users/owenmurray/Desktop/untitled folder/untitled folder/transcribe.txt') as my_new_file:
contents = my_new_file.read()
partner_file = open('/Users/owenmurray/Desktop/untitled folder/untitled folder/P.txt')
with open('/Users/owenmurray/Desktop/untitled folder/untitled folder/follow_up_question.txt') as follow_up_question_file:
follow_up = follow_up_question_file.read()
partners = partner_file.readlines()
# Converts it to a list
lines = contents.split("\n")
follow_up_list = follow_up.split("\n")
for p in partners:
try:
output = None
for index, line in enumerate(lines):
if p.strip() in line:
output = index
break
if output:
print ("\n" + lines[output] + "\n")
print("-------------------------------------------------------------")
print("\n" + lines[output +1] + "\n")
if "yes" in lines[output +1].lower() or "yeah" in lines[output + 1].lower():
print("-------------------------------------------------------------")
print ("\n" + lines[output +2] + "\n")
try:
for follow in follow_up_list():
if follow in lines[output+2].lower():
True
print("-------------------------------------------------------------")
print ("\n" + lines[output +3] + "\n")
break
except (ValueError):
print("Nothing found")
break
except:
pass
An example of my transcript can be found here:
https://paste.pythondiscord.com/obucaweyuc.py
My p.txt can be found here:
have you spoken with a ARM partner in the last six months
And my follow_up_questions.txt has:
did you talk about similar issues?
However the current output only displays:
ch_0 : have you spoken with a ARM partner in the last six months
about having a discussion about how ARM those, um, quality
security could benefit you guys?
ch_1 : Yeah, we have
ch_0 : Oh, okay and did you talk about similar issues?
I have cleaned up your code a bit just to try to simplyfy the problem. I have included the output it produces, as per your comment it gives the line after
with open('transcribe.txt') as t_file, open('p.txt') as p_file, open('follow_up_question.txt') as f_file:
t_lines = t_file.readlines()
f_lines = f_file.readlines()
p_lines = p_file.readlines()
for p_line in p_lines:
for index, line in enumerate(t_lines):
if p_line.strip() in line:
print(f'{t_lines[index]}{"-"*30}\n{t_lines[index + 1]}', end='')
if "yes" in t_lines[index + 1].lower() or "yeah" in t_lines[index + 1].lower():
print(f'{"-"*30}\n{t_lines[index + 2]}', end='')
for follow in f_lines:
if follow in t_lines[index + 2].lower():
print(f'{"-"*30}\n{t_lines[index + 3]}', end='')
OUTPUT
ch_0 : have you spoken with a ARM partner in the last six months about having a discussion about how ARM those, um, quality security could benefit you guys?
------------------------------
ch_1 : Yes, we have
------------------------------
ch_0 : Oh, okay and did you talk about similar issues?
------------------------------
ch_0 : Okay, Uh, would you be willing to, um, have a discussion with ARM partner? Um, it's project making business sense
However just for your reference the issue in your code was this line
for follow in follow_up_list():
follow_up_list is a python list and is not callable so you need to drop the parentheses
for follow in follow_up_list:
Related
I'm working on a projects that shows basic user details.
Here's the respective code that I'm having problem with.
#wrap
def show(self, *ids):
for id in ids:
try:
user = self.api.get_user(id)
print(user.name.center(80, '~'))
print('%d Followers %d Following'.center(80, '~') %
(user.followers_count, user.friends_count))
except Exception:
print('Error')
finally:
print()
The code shows both the lines with the max-width of 80 chars.
At this point it should only print maximum of 80 chars on each line.
But I'm getting this output :
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Twitter~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~58312564 Followers 1 Following~~~~~~~~~~~~~~~~~~~~~~~~~~~
The first line is seems perfect but the second line is really not looking at the center.
I read the docs and I also tried using .format() inside the print statement but I'm getting the same problem.
How can I print both the line contents at the center?
(One character difference is considerable)
Please help.
Does This work for you?
followers_count= 5831256
friends_count = 1
var = f" {followers_count} Followers {friends_count} Following "
print(f"{' Twitter ':~^80}")
print(f"{var:~^80}")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Twitter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~ 5831256 Followers 1 Following ~~~~~~~~~~~~~~~~~~~~~~~~
Adapt it to your method definition.
Note: var is unnecessary
I am trying to execute this but not able to.
Can someone assist?
teamname1 = print(input((plyer1,' Name of your team? '))
teamname2 = print(input(plyer2,' Name of your team? '))
print(teamname1)
print(teamname2)
Three issues:
the first line contains one parenthesis too many
input() takes only one argument, the prompt. If plyer1 is a
string, you must concatenate it
same as in comment: print() does not return anything, and can be
omitted because the prompt of the input() command is already
displayed.
You probably need something like this:
plyer1 = 'parach'
plyer2 = 'amk'
teamname1 = input(plyer1 + ' Name of your team? ')
teamname2 = input(plyer2 + ' Name of your team? ')
print(teamname1)
print(teamname2)
I'm not exactly sure what you're trying to do with the teamname variables. If you could modify the question/code it would help a lot.
As far as print and input on the same line, I think this might be what you're going for.
print("player1" + " " + input("Name of your team: "))
print("player2" + " " + input("name of your team: "))
P.S. There are many tutorials on-line that could help. Make sure to look around first, then come here.
I have a code that allows a user to choose between 3 options
Ie; Beginner: 1, Intermediate: 2 and Advanced: 3.
However, I'm wanting to generate a paragraph that's assigned to each of the 3 options.
For example
If the user has entered 1 for Beginner, the output will follow with "Hi Beginner! We are going to learn about ....."
The code I've tried thus far is just using the print(" ")option followed by
if f==0:
print("You have entered " + str(inp) + ": " + out).
However, as I'm writing a long paragraph, the output is messy.
Well, i think that you're printing a line without using "\n" in your print text, that's why the output will be always a entire line.
You can use "\n" to write different lines:
print("This is a line\nNow this is other")
Or you can use triple quotes:
print("""This is a line
Now this is other""")
I'm teaching myself python and I'm making some changes to a bot that someone else wrote.
I'm trying to add a filter for words that NSFW or not kid friendly. I've added these words to a list called config.banned_name_keywords.
I had it working originally by returning the whole tweet, but I'm trying to return the SPECIFIC word that was found so I can troubleshoot and edit the list.
I can return the whole tweet with tweet.text but that takes away from the output and clogs up the screen.
I've also tried print(x) but I can't tell where that's being defined. It's returning the word that found the tweet in the first place.
for tweet in searched_tweets:
if any(rtwords in tweet.text.lower().split() for rtwords in config.retweet_tags):
# The script only cares about contests that require retweeting. It would be very weird to not have to
# retweet anything; that usually means that there's a link you gotta open and then fill up a form.
# This clause checks if the text contains any retweet_tags
if tweet.retweeted_status is not None:
# In case it is a retweet, we switch to the original one
if any(y in tweet.retweeted_status.text.lower().split() for y in config.retweet_tags):
tweet = tweet.retweeted_status
else:
continue
if tweet.user.screen_name.lower() in config.banned_users or any(x in tweet.user.name.lower() for x in config.banned_name_keywords):
# If it's the original one, we check if the author is banned
print("Avoided user with ID: " + tweet.user.screen_name + " & Name: " + tweet.user.name)
continue
elif any(z in tweet.text.lower().split() for z in config.banned_name_keywords):
# If the author isn't banned, we check for words we don't want
print("Avoided tweet with words:" + z)
continue
Not now, but you will be able to in Python 3.8 via assignment expressions:
elif any((caught := z) in tweet.text.lower().split() for z in config.banned_name_keywords):
print("Avoided tweet with word: " + caught)
If you want to catch all the banned words that might appear, you can't use any, since its purpose is to stop as soon as you find one match. For this, you just want to compute the intersection instead (which you can do today as well):
banned = set(config.banned_name_keywords)
...
else:
caught = banned.intersection(tweet.text.lower().split())
if caught:
print("Avoided tweet with banned words: " + caught)
(That itself can be shortened using assignment expressions as well:
elif (caught := banned.intersection(tweet.text.lower().split())):
print("Avoided tweet with banned words: " + caught)
)
Change this line
if tweet.user.screen_name.lower() in config.banned_users or any(x in tweet.user.name.lower() for x in config.banned_name_keywords):
to
try:
# matched_banned_keyword below is the `SPECIFIC` word that matched
matched_banned_keyword = config.banned_name_keywords[config.banned_name_keywords.index(tweet.user.name.lower())]
except:
matched_banned_keyword = None
if tweet.user.screen_name.lower() in config.banned_users or matched_banned_keyword:
print("Avoided user with ID: " + tweet.user.screen_name + " & Name: " + tweet.user.name)
L.index(x) function returns the index of the x in the list L and raises an exception if x is not present in the list L. You can catch the exception which will occur in your case when user.screen_name.lower() is not present in config.banned_name_keywords
I am trying to read from a file and return solutions based on the problem that the user inputs. I have saved the text file in the same location, that is not an issue. At the moment, the program just crashes when I run it and type a problem eg "screen".
Code
file = open("solutions.txt", 'r')
advice = []
read = file.readlines()
file.close()
print (read)
for i in file:
indword = i.strip()
advice.append (indword)
lst = ("screen","unresponsive","frozen","audio")
favcol = input("What is your problem? ")
probs = []
for col in lst:
if col in lst:
probs.append(col)
for line in probs:
for solution in advice:
if line in solution:
print(solution)
The text file called "solutions.txt" holds the following info:
screen: Take the phone to a repair shop where they can replace the damaged screen.
unresponsive: Try to restart the phone by holding the power button for at least 4 seconds.
frozen: Try to restart the phone by holding the power button for at least 4 seconds.
audio: If the audio or sound doesnt work, go to the nearest repair shop to fix it.
Your question reminds me a lot of my learning, so I will try give an answer to expand on your learning with lots of print statements to consider how it works carefully. It's not the most efficient or stable approach but hopefully of some use to you to move forwards.
print "LOADING RAW DATA"
solution_dictionary = {}
with open('solutions.txt', 'r') as infile:
for line in infile:
dict_key, solution = line.split(':')
print "Dictionary 'key' is: ", dict_key
print "Corresponding solution is: ", solution
solution_dictionary[dict_key] = solution.strip('\n')
print '\n'
print 'Final dictionary is:', '\n'
print solution_dictionary
print '\n'
print 'FINISHED LOADING RAW DATA'
solved = False
while not solved: # Will keep looping as long as solved == False
issue = raw_input('What is your problem? ')
solution = solution_dictionary.get(issue)
""" If we can find the 'issue' in the dictionary then 'solution' will have
some kind of value (considered 'True'), otherwise 'None' is returned which
is considered 'False'."""
if solution:
print solution
solved = True
else:
print ("Sorry, no answer found. Valid issues are 'frozen', "
"'screen' 'audio' or 'unresponsive'")
want_to_exit = raw_input('Want to exit? Y or N? ')
if want_to_exit == 'Y':
solved = True
else:
pass
Other points:
- don't use 'file' as a variable name anywhere. It's a python built-in and can cause some weird behaviour that you'll struggle to debug https://docs.python.org/2/library/functions.html
- If you get an error, don't say "crashes", you should provide some form of traceback e.g.:
a = "hello" + 2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-6f5e94f8cf44> in <module>()
----> 1 a = "hello" + 2
TypeError: cannot concatenate 'str' and 'int' objects
your question title will get you down-votes unless you are specific about the problem. "help me do something" is unlikely to get a positive response because the error is ambiguous, there's no sign of Googling the errors (and why the results didn't work) and it's unlikely to be of any help to anyone else in the future.
Best of luck :)
When I change the line "for i in file:" to "for i in read:" everything works well.
To output only the line starting with "screen" just forget the probs variable and change the last for statement to
for line in advice:
if line.startswith( favcol ) :
print line
break
For the startswith() function refer to https://docs.python.org/2/library/stdtypes.html#str.startswith
And: the advices of roganjosh are helpfull. Particularly the one "please don't use python keywords (e.g. file) as variable names". I spent hours of debugging with some bugs like "file = ..." or "dict = ...".