我是Python的新手,一直在解决一个问题。我已经编写了代码来识别多个文件的总字数和唯一字数(在这种情况下,.txt文件是一本书的章节:来自文件1的示例文本)它在什么时间段引起可变性的原因,无论它们可能是什么,通常起作用,都有争议;无论是在胚胎发育的早期或晚期,还是在受孕的瞬间,“文件样本文本2”最后,变种与物种具有相同的一般特征,因为它们无法与物种区分,除非首先通过发现中间连接形式)。你知道吗
我在网上找不到任何关于如何在文件之间比较单词的例子。我需要确定文件之间共享的字数以及每个文件(相对于其他文件)唯一的字数。我的最终输出应该包括7个数字:file1和file2的总字数,file1和file2的唯一字数,file1和file2之间共享的字数,file1中但不在file2中的字数,以及file2中但不在file1中的字数。我知道我必须使用set()来做这件事,但我不明白怎么做。你知道吗
import glob
from collections import Counter
path = "c-darwin-chapter-?.txt"
wordcount = {}
for filename in glob.glob(path):
with open("c-darwin-chapter-1.txt", 'r') as f1, open("c-darwin-chapter-2.txt", 'r') as f2:
f1_word_list = Counter(f1.read().replace(',','').replace('.','').replace("'",'').replace('!','').replace('&','').replace(';','').replace('(','').replace(')','').replace(':','').replace('?','').lower().split())
print("Total word count per file: ", sum(f1_word_list.values()))
print("Total unique word count: ", len(f1_word_list))
f2_word_list = Counter(f2.read().replace(',','').replace('.','').replace("'",'').replace('!','').replace('&','').replace(';','').replace('(','').replace(')','').replace(':','').replace('?','').lower().split())
print("Total word count per file: ", sum(f2_word_list.values()))
print("Total unique word count: ", len(f2_word_list))
#if/main commented out but final code must use if/main and loop
#if __name__ == '__main__':
# main()
期望输出:
Total word count
Chapter1 = 11615
Chapter2 = 4837
Unique word count
Chapter1 = 1991
Chapter2 = 1025
Words in Chapter1 and Chapter2: 623
Words in Chapter1 not in Chapter2: 1368
Words in Chapter2 not in Chapter1: 402
读入两个文件并将读取的文本转换为列表/集。使用集合,可以使用集合运算符计算它们之间的交点/差值:
演示:
输出:
你已经在处理文件读取和“统一”到小写-我忘在这里了。输出使用python3.6的字符串插值语法:参见PEP 498
相关问题 更多 >
编程相关推荐