【问题标题】:How can I find and count multiple intersections between a list and a text?如何查找和计算列表和文本之间的多个交叉点?
【发布时间】:2016-02-22 02:02:11
【问题描述】:

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

abchecken
abchillen
abdancen
abdimmen
abfall-container
abflug-terminal

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

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

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”出现在文本中,则此事件将被忽略。我该如何解决?

来自瑞士的亲切问候!

【问题讨论】:

  • 您是否正在寻找类似:sorted([{w:text.count(w)} for w in words]) 的内容?

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


【解决方案1】:

我会这样做:

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)])

【讨论】:

  • 只在开头就足够了,因为大多数英国主义在结尾都被拒绝了,例如动漫 -> 动漫
  • @boban 添加了如何匹配以英语开头的字符串。如果您有太多的 anglicisms,或者可能将您的 anglicism 列表分成不同的列表(例如通过起始字符),那么预构建正则表达式可能会更快
【解决方案2】:

这解决了你的第一个问题:

anglicisms = ["a", "b", "c"]
words = ["b", "b", "b", "a", "a", "b", "c", "a", "b", "c", "c", "c", "c"]

results = map(lambda angli: (angli, words.count(angli)), anglicisms)
results.sort(key=lambda p:-p[1])

结果如下所示:

[('b', 5), ('c', 5), ('a', 3)]

对于第二个问题,我认为正确的方法是使用正则表达式。

【讨论】:

  • 正则表达式很吓人!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多