[英]process and export text file into csv file
我正在使用此代码来获取文本文件作为输入,并将其转换为csv文件作为输出。 csv文件有两列,一列用于单词,另一列用于单词计数。
from collections import Counter
file = open(r"/Users/abdullahtammour/Documents/txt/1984/1984.txt", "r", encoding="utf-8-sig")
wordcount={}
wordcount = Counter((file.read().split()))
for item in wordcount.items():
print("{}\t{}".format(*item), file=open("/Users/abdullahtammour/Documents/txt/1984/1984.csv", "a"))
file.close()
我想增强代码并添加两个功能:第一个(也是最重要的)我只希望输出文件中的单词,没有数字,没有诸如(*&-//。,!?)之类的字符。 2nd将输出文件中的所有单词变为小写。
任何帮助将不胜感激。
您可以使用字符串方法isalpha()来检查单词中是否只有字母字符,还可以使用lower()将其转换为小写。 我假设您也不想在单词中使用撇号或其他标点符号,但是如果可以的话,您可以使用replace去除此类字符,如下所示:
word.replace("'",'').isalpha()
与打开和关闭文件一千次相比,打开文件一次也要好,这是通过在循环主体中打开文件来完成的。 如果涉及缓冲,它不仅效率低下,而且可以想象得到奇怪的结果。
我用'with'子句重写了它,该子句大致等于在子句的开头打开文件,然后在结尾关闭文件。
不那么重要,但是您可以在print()中使用'sep'关键字,而不是手动插入标签,如下所示:
print(arg1, arg2, sep='\t')
修改您的代码:
from collections import Counter
file = open(r"/Users/abdullahtammour/Documents/txt/1984/1984.txt", "r", encoding="utf-8-sig")
wordcount={}
wordcount = Counter((file.read().split()))
file.close()
with open("/Users/abdullahtammour/Documents/txt/1984/1984.csv", "w") as file:
for word, count in wordcount.items():
if word.isalpha():
print(word.lower(), count, sep='\t', file=file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.