【发布时间】:2020-10-07 03:07:50
【问题描述】:
我对 python 还很陌生,我想弄清楚为什么我的函数没有给我我正在寻找的输出。我觉得我已经尝试了一切并尝试研究,但我没有找到任何对我有帮助的东西。
这是我的代码:
from sys import argv
def GetCharactersWords(input):
characters = input.read()
words = len(characters.split())
#word = len(words)
return words
def GetCharacterNumber(input):
characters = input.read()
number = characters.count(".")
return number
def FirstSentence(input):
characters = input.read()
fields = characters.split(".")
field1 = fields[0]
return field1
def LengthFirstSentence(input):
characters = input.read()
fields = characters.split(".")
field1 = fields[0]
field0 = len(field1)
return field0
def LastSentence(input):
characters = input.read()
fields = characters.split(".")
field2 = fields[-1]
return field2
def LengthLastSentence(input):
characters = input.read()
fields = characters.split(".")
field3 = fields[-1]
field4 = len(field3)
return field4
def print_to_file(word_characters, number_characters, first_sentence, length_first,
last_sentence, length_last):
with open("output.txt", "w") as outfile:
outfile.write("Here is the text file: " + '\n')
outfile.write(str(input) + '\n')
outfile.write("Number of words in the file?" + '\n')
outfile.write(str(word_characters) + '\n')
outfile.write("Number of sentences in the file?" + '\n')
outfile.write(str(number_characters) + '\n')
outfile.write("First sentence in the file?" + '\n')
outfile.write(str(first_sentence) + '\n')
outfile.write("Last sentence in the file?" + '\n')
outfile.write(str(last_sentence) + '\n')
outfile.write("Length of the first sentence" + '\n')
outfile.write(str(length_first)+ '\n')
outfile.write("Length of the last sentence" + '\n')
outfile.write(str(length_last) + '\n')
outfile.close()
def main(argv):
script = argv[0]
filename = argv[1]
input = open(filename, "r")
word_characters = GetCharactersWords(input)
number_characters = GetCharacterNumber(input)
first_sentence = FirstSentence(input)
length_first = LengthFirstSentence(input)
last_sentence = LastSentence(input)
length_last = LengthLastSentence(input)
file_print = print_to_file(word_characters, number_characters, first_sentence, length_first,
last_sentence, length_last)
if __name__ == '__main__':
main(argv)
这是它给我的输出:
Here is the text file:
<built-in function input>
Number of words in the file?
2430
Number of sentences in the file?
0
First sentence in the file?
Last sentence in the file?
Length of the first sentence
0
Length of the last sentence
0
我不明白为什么它没有给我不同的输出。
感谢您的帮助!
【问题讨论】:
-
您的每个函数都读取整个文件,将当前文件位置留在文件的最后——因此您在第一个函数之后调用的每个函数都没有可读取的内容。每次重新打开文件,通过
.seek(0)将其倒回到开头,或者在main()中读取文件一次并将内容传递给每个函数。 (请注意,input是该文件的错误名称,因为它覆盖了 Python 内置函数)。 -
顺便说一句,欢迎来到 SO!如果您需要建议,请查看tour 和How to Ask。例如,制作minimal reproducible example 非常有帮助。您发布了很多代码,其中大部分与问题无关。