这是我的代码。它将URL拆分为各个组成部分,然后读取URL并将其打印到屏幕上。之后,它应该显示字符数,但是没有显示,我不确定如何解决。
import urllib.request
import urllib.error
import urllib.parse
from urllib.parse import urlparse
def welcome():
# asks user for name
name = input('Please enter your name:\nPress "2" to exit.')
# if 2 is typed, program ends
if name == '2':
# prints message
print('Goodbye!')
# exits
exit
else:
# prints user name and explains program
print('Welcome to the program',name,'!', "This program will ask for a url then get the domain name and convert the url to a text file and count the words in it.")
# takes user to main
main()
def main():
try:
# asks user what file they want to open
url = input('Please enter a url.\nPress "2" to quit.\n')
if url == ('2'):
# prints message and exits
print('Goodbye')
# exits
exit
else:
# prints url
print(url)
# parses the url for the scheme
scheme = urlparse(url).scheme
# prints the scheme
print("The scheme of the URL is: ", scheme)
# parses the url for the domain
domain = urllib.parse.urlsplit(url)[1].split(':')[0]
# prints the domain
print ("The domain name of the url is: ", domain)
# parses the url for the path
path = urlparse(url).path[1:]
# prints the path
print("The path of the url is: ", path)
# pauses for the user
input("Press 'Enter' to retrieve and print the webpage.")
# prints out webpage
print("Here is the webpage:")
# requests to open the webpage
fhand = urllib.request.urlopen(url)
for line in fhand:
print(line.decode().strip())
input("Press 'Enter' to count the overall number of characters in the document.")
characters = 0
for line in fhand:
words = line.decode()
characters = characters + len(words)
print(characters)
# pauses for user
input('Press "Enter" to do it again or exit.')
# takes user to repeat function
repeat()
except:
# if there is an error, code goes here
print('Error. Cannot open webpage. Try again.')
# takes user back to main
main()
def repeat():
# asks user if they would like to repeat or do another search
choice = input("Would you like to use another url? \nPress '1' to repeat.\nPress '2' to exit.\n")
# if 1 is typed program goes through the letter function then back to repeat
if choice == '1':
# takes user back to main
main()
# if 2 is typed program exits
elif choice == '2':
# prints message
print('Goodbye!')
# exists program
exit
else:
# prints message
print('Something went wrong. Try again.')
# takes user back to main
main()
welcome()
一切正常,直到出现在柜台上,并显示为:
{}
我在网上寻求其他帮助,该部分的代码完全相同,但在我的产品中不起作用。