python - 如何查找和计算列表和文本之间的多个交集?

标签 python python-3.x text text-files intersection

我目前正在使用 Python 编写一个程序来计算德语文本中的英国化程度。我想知道整个文本中出现了多少次英语化。为此,我列出了德语中所有英国化的列表,如下所示:

abchecken
abchillen
abdancen
abdimmen
abfall-container
abflug-terminal

名单还在继续…… 然后我检查了这个列表和要分析的文本之间的交叉点,但这只给我一个出现在两个文本中的所有单词的列表,例如:Anglicisms : 4:{'abdancen', 'abchecken ', '终端'}

我真的很想输出这些单词出现的次数(最好按频率排序),例如:

Anglicisms: abdancen(5), abchecken(2), terminal(1)

这是我目前的代码:

 #counters to zero
 lines, blanklines, sentences, words = 0, 0, 0, 0

 print ('-' * 50)

 while True:
     try:
       #def text file
       filename = input("Please enter filename: ")
       textf = open(filename, 'r')
       break
     except IOError:
       print( 'Cannot open file "%s" ' % filename )

 #reads one line at a time
 for line in textf:
   print( line, )  # test
   lines += 1

   if line.startswith('\n'):
     blanklines += 1
   else:
     #sentence ends with . or ! or ?
    #count these characters
     sentences += line.count('.') + line.count('!') + line.count('?')

     #create a list of words
     #use None to split at any whitespace regardless of length
     tempwords = line.split(None)
     print(tempwords)

     #total words
     words += len(tempwords)

 #anglicisms
     words1 = set(open(filename).read().split())
     words2 = set(open("anglicisms.txt").read().split())

     duplicates  = words1.intersection(words2)


 textf.close()
 print( '-' * 50)
 print( "Lines       : ", lines)
 print( "Blank lines : ", blanklines)
 print( "Sentences   : ", sentences)
 print( "Words       : ", words)
 print( "Anglicisms  :  %d:%s"%(len(duplicates),duplicates))

我遇到的第二个问题是它没有计算那些换句话说的英国化。例如,如果“big”在英国语列表中,而“bigfoot”在文本中,则忽略这种情况。我该如何解决?

来自瑞士的亲切问候!

最佳答案

我会做这样的事情:

from collections import Counter
anglicisms = open("anglicisms.txt").read().split()

matches = []
for line in textf:
    matches.extend([word for word in line.split() if word in anglicisms])

anglicismsInText = Counter(matches)

关于第二个问题,我觉得有点难做。以你的例子为例,“big”是一种英国主义,“bigfoot”应该匹配,但是“Abigail”呢?还是“过”?每次在字符串中发现英语时它都应该匹配吗?一开始?在最后?一旦你知道了,你应该构建一个匹配它的正则表达式

编辑:要匹配以英语开头的字符串,请执行以下操作:

def derivatesFromAnglicism(word):
    return any([word.startswith(a) for a in anglicism])

matches.extend([word for word in line.split() if derivatesFromAnglicism(word)])

关于python - 如何查找和计算列表和文本之间的多个交集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33812181/

相关文章:

android - 如何在屏幕上显示文本编辑框 "over"?

text - 清除 TextField 时如何恢复占位符文本

android - 如何在 TextView 中动态更改字体样式?

python - 比较 2 个 ML 模型的性能准确性之间的差异是否具有统计显着性

python - 从单独的数据帧 pandas 中最接近的时间戳中提取信息

python - 使用 python3 和 raspberry pi3 的两个按钮 react 游戏

python - 如何阻止 python 程序可执行文件打开 cmd shell?

python - 即使我正确初始化,为什么还是收到 'cuMemAlloc failed: not initialized'?

java - Java Collections Framework 的 Python 等价物是什么?

python - 否则缩进错误: unexpected unindent in PyCharm