[英]Creating text file containing unique words from an input text file
I have written a code to create a text file containing all the unique words from another text file.我编写了一个代码来创建一个文本文件,其中包含来自另一个文本文件的所有唯一单词。 However I am not getting any output.但是我没有得到任何输出。 though the code is running without error.虽然代码运行没有错误。
Input text file , g.txt :输入文本文件,g.txt:
I am not a robot I am a human I am a girl I am not a woman I am a school girl I go to high school我不是机器人 我是人 我是女孩 我不是女人 我是女学生 我上高中
The text file can have blank lines or spaces.文本文件可以有空行或空格。
My code is as follows :我的代码如下:
def unique_file(input_filename, output_filename):
input_file = open('g.txt', 'r')
file_contents = input_file.read()
word_list = file_contents.split()
file = open('n.txt', 'w')
unique_words = set(word_list)
for word in unique_words:
file.write(str(word) + "\n")
file.close()
The program is not creating the output file n.txt.该程序未创建输出文件 n.txt。
Any suggestions ?有什么建议 ?
You forgot to call the function:你忘了调用函数:
def unique_file(input_filename, output_filename):
with open(input_filename) as input_file:
file_contents = input_file.read()
word_list = file_contents.split()
file = open(output_filename, 'w')
unique_words = set(word_list)
for word in unique_words:
file.write(str(word) + "\n")
file.close()
if __name__ == "__main__":
unique_file('g.txt', 'n.txt')
Here's a more optimized version of your code:这是您的代码的更优化版本:
def unique_file(input_filename, output_filename):
with open(input_filename) as infile, open(output_filename, 'w') as outfile:
file_contents = infile.read()
word_list = file_contents.split()
unique_words = set(word_list)
for word in unique_words:
outfile.write(str(word) + "\n")
if __name__ == "__main__":
unique_file('g.txt', 'n.txt')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.