How can I display messages in single line in a webpage using flask? I have tried the following:
lines=sent_tokenize(s)
sentence_count=len(lines)
flash("no of sentences :",sentence_count)
but the sentence_count is not displayed.
Not exactly sure if this is correct, since I'm missing a lot of context, but try below
lines=sent_tokenize(s)
sentence_count=len(lines)
flash("no of sentences: %d" % sentence_count)
Since flash seems to take a string as the first parameter, and len returns an integer, put sentence_count inside the "no of sentences" string
While using python 3.7.6 there are several option to do that
"no of sentences: {0}".format(sentence_count)
"no of sentences: {count}".format(count=sentence_count)
"no of sentences: %d" % sentence_count # %d for int, %s for string
f'no of sentences: {sentence_count}'
Related
I am searching for a string in .gz files and trying to print the last line with a specific string. It is giving me 'list Index is out of range' if the string is not present. Below is the code I was working on
with gzip.open(files, 'r') as r, open ('output.txt', 'w') as w:
string = [line.strip() for line in r.readlines() if b'STRING' in line]
print (string[-1])
With the above code, I can print the last line if the 'STRING' is in the file. If it is not present it is throwing an error. In the else case, I would like to print "NO STRING PRESENT" or something like that. Any help in understanding this will really be helpful. Thanks in advance
Use try-except:
try:
print (string[-1])
except:
print ("NO STRING PRESENT")
or write your own conditional. Start thinking on the lines of the list string itself, what its length would be in either case and then what would you want to do for each case.
For school I need to write a code that will play Hangman with you but, there is a error which I can't fix. The error is in the part of the print, I think it has something to do with the import but I am not sure (the error is a invalid syntax)
I tried to put the print and the message on different lines but I didn't work, I also tried a colon behind the print but also that didn't solve the problem (I am in Python 3.6.1 on repl.it)
https://repl.it/#Informatica132/Galgje
It has to print: "Your right" Character "is in the chosen word", or "Your wrong" Character "is not in the chosen word" but it prints a syntaxerror invalid syntax.
Errors, errors everywhere. I have fixed all the syntax errors, but you still need to figure out your program logic. (Currently it lets you guess a single letter before exiting.)
import random
Trys = 0
Words = ["Hey" , "Hello" , "mate" , "victory" , "wineglass" , "UK"]
Word = (random.choice(Words))
Character = str(input("type one character to look if it is in the chosen word"))
if Character in Word:
print ("Your right", Character, "is in the chosen word")
Trys = Trys + 1
else:
print ("Your wrong", Character, "is not in the chosen word")
Trys = Trys + 1
I have a list with a bunch of lines (created from a 'show cdp neighbors detail
from a Cisco switch or router).
I want to perform some processing but only on lines that contain one of the following four strings:
important = (
"show cdp neighbors detail",
"Device ID: ",
"IP address: ",
"Platform: "
)
Right now my iterations work but I am processing over a large number of lines that end up doing nothing. I simply want to skip over the unimportant lines and do my processing over the four lines lines that contain the data that I need.
What I want to do (in English) is:
for line in cdp_data_line:
if any of the lines in 'cdp_data_line' does not contain one of the four strings in 'important', then continue (skip over the line).
After skipping the unwanted lines, then I can test to see which of the four lines I have left and process accordingly:
if all of the four strings in 'important' is not found in any line of cdp_data_line, the continue
if any of those four strings is found in a line,then process:
elif 'show cdp neighbors detail' in line:
do something
elif 'Device ID: ' in line:
do something
elif 'IP address: ' in line:
do something
elif 'Platform: ' in line:
do something
else:
sys.exit("Invalid prompt for local hostname - exiting")
I am trying to do it like this:
if any(s in line for line in cdp_data_line for s not in important):
continue
PyCharm says it doesn't know what 's' is, even though I found code snippets
using this technique that work in PyCharm. Not sure why mine is failing.
There has got to be a succinct way of saying: If string1 or string 2 or string 3 or string 4 is not in cdp_data_line, then skip (continue), otherwise
if I find any of those four strings, do something.
Any help would be greatly appreciated.
I'm trying to write code that analyses a sentence that contains multiple words and no punctuation. I need it to identify individual words in the sentence that is entered and store them in a list. My example sentence is 'ask not what your country can do for you ask what you can do for your country. I then need the original position of the word to be written to a text file. This is my current code with parts taken from other questions I've found but I just can't get it to work
myFile = open("cat2numbers.txt", "wt")
list = [] # An empty list
sentence = "" # Sentence is equal to the sentence that will be entered
print("Writing to the file: ", myFile) # Telling the user what file they will be writing to
sentence = input("Please enter a sentence without punctuation ") # Asking the user to enter a sentenc
sentence = sentence.lower() # Turns everything entered into lower case
words = sentence.split() # Splitting the sentence into single words
positions = [words.index(word) + 1 for word in words]
for i in range(1,9):
s = repr(i)
print("The positions are being written to the file")
d = ', '.join(positions)
myFile.write(positions) # write the places to myFile
myFile.write("\n")
myFile.close() # closes myFile
print("The positions are now in the file")
The error I've been getting is TypeError: sequence item 0: expected str instance, int found. Could someone please help me, it would be much appreciated
The error stems from .join due to the fact you're joining ints on strings.
So the simple fix would be using:
d = ", ".join(map(str, positions))
which maps the str function on all the elements of the positions list and turns them to strings before joining.
That won't solve all your problems, though. You have used a for loop for some reason, in which you .close the file after writing. In consequent iterations you'll get an error for attempting to write to a file that has been closed.
There's other things, list = [] is unnecessary and, using the name list should be avoided; the initialization of sentence is unnecessary too, you don't need to initialize like that. Additionally, if you want to ask for 8 sentences (the for loop), put your loop before doing your work.
All in all, try something like this:
with open("cat2numbers.txt", "wt") as f:
print("Writing to the file: ", myFile) # Telling the user what file they will be writing to
for i in range(9):
sentence = input("Please enter a sentence without punctuation ").lower() # Asking the user to enter a sentenc
words = sentence.split() # Splitting the sentence into single words
positions = [words.index(word) + 1 for word in words]
f.write(", ".join(map(str, positions))) # write the places to myFile
myFile.write("\n")
print("The positions are now in the file")
this uses the with statement which handles closing the file for you, behind the scenes.
As I see it, in the for loop, you try to write into file, than close it, and than WRITE TO THE CLOSED FILE again. Couldn't this be the problem?
This is the coding that I have so far. The basic concept is that you have a separate file to type in the answers and then the program accesses the separate file and draws information from it.
#!/usr/bin/python3.2
# -*-coding:Utf-8 -*
#Vocabulary/translation quiz
import os
import random
keep_adding=input("Would you like to start a new quiz ? If yes, press \"S\" : ")
with open("data.txt","a") as f: #look for the file data.txt for the questions
while keep_adding=="S": #ongoing action to look for the answer
word=input("Enter a word : ")
translation=input("And its translation : ")
f.write("{0},{1},\n".format(word,translation))
keep_adding=input("To continue, press \"O\" : ")
#in case the file doesn't exist, we create one :
with open("data.txt","a") as f:
pass
os.system('clear')
print("* * * QUIZ STARTS! * * *") #this shows the quiz has started after 'o' input
with open("data.txt","r") as f:
question = [line.split(",") for line in f]
i = 0
score = 0 #variables
while i<len(question):
num = random.randint(0,len(question)-1) #creates random question from the list
print("\nQuestion number", i+1,": \nWhat is the translation for", question[num][0], "?")
answer = input("Answer :")
if (answer == str(question[num][1])):
print("Congratulations! That's the good answer!")
score += 1
else:
print("Wrong. The correct answer was :",question[num][1]) #just tells you the wrong answer
i += 1
if len(question)==0:
print("\nThe file is empty. Please add new words to start the quiz !\n")
else:
if i>1:
qu_pl = "questions"
else:
qu_pl = "question"
if score>1:
sc_pl = "answers"
else:
sc_pl = "answer"
print("\n RESULTS :\n ",i, qu_pl,", ",score,"correct ",sc_pl," \n"\
," --> Your score is : ",score*100/i,"% !\n")
The basic concept is that you have a separate file to type in the answers and then the program accesses the separate file and draws information from it.
My problem; the program accesses this file and successfully gains the information but when you actually try to run the program with multiple answers (in my case a 32 answer German Vocab test), the program doesn't mark the answers as right. Have tried many alternatives and it does work with single answers in a .txt document.
If someone has any knowledge and could help me, it would be much appreciated! :)
My .txt questions and answers are set out like this;
beliebt,popular
eng,narrow
Thanks for any help!! <3
The program listed works for me as is (using Python 3.3.2). If you want it to work with multiple possible answers for one word (not sure if that's what you meant), you can use
if (answer in question[num][1:]):
instad of
if (answer == str(question[num][1])):
you might also want to strip any spaces from your sample answers:
for i in range(len(question)):
for j in range(len(question[i])):
question[i][j] = question[i][j].strip(' ')
use lstrip and rstrip if you want to have spaces inside the answer.
Then you can add multiple answers just like this:
What is the translation for eng?
narrow, tight