源于我想写一个小工具,统计我学习到的英语单词,去重之后再统计给我目前掌握的单词量;
我的需求:
1、输入单词,或者句子(用空格隔开)
2、读取单词,并将单词首字母大写
3、写入一个txt的文档中
1)文档中单词应去重
2)单词按照字母进行排序
3)统计这个txt中单词总数
我初步的实现代码见下:
还有很多不完善的,希望大家有更好的实现代码,能一起交流~~~
import re
a = input("请输入想记录的单词或句子:")
words = re.split(r"\s+", a)
lenth = len(words)
fileName = 'test1.txt'
def get_file_word():
# 写入单词
for i in range(lenth):
single = words[i]
formatDaxie = single.capitalize()
with open("word.txt", "a") as f:
f.write(formatDaxie)
f.write(' ')
f.close()
def word_reduction():
# 去重
f = open("word.txt","r", encoding='utf-8')
# 将文件读出来
lines = f.read()
# 以空格分隔成ls,再转成元组去重后,再重新转回list,进行统计单词数
ls = lines.split()
ls_temp = set(ls)
words = list(ls_temp)
words.sort()
# 统计总共有多少单词
count = len(words )
# 将单词排序
print(count)
print(words)
f = open("word.txt","w", encoding='utf-8')
f.write(' '.join(str(word) for word in words ))
f.close()
if __name__ == '__main__':
get_file_word()
word_reduction()