【问题标题】:Searching a .txt file for multiple list terms and outputting counts/%/words在 .txt 文件中搜索多个列表项并输出 counts/%/words
【发布时间】:2019-05-18 00:26:36
【问题描述】:

我正在尝试在给定的 .txt 文件 (source_filename) 中搜索一系列列表术语,并提供它们的计数输出、.txt 文件中这些术语的百分比以及找到的每组列出的术语的确切单词在文本中。

我应该如何设置计数/报告功能?


#build GUI for text file selection
import PySimpleGUI as sg      
window_rows = [[sg.Text('Please select a .txt file for analysis')],      
                 [sg.InputText(), sg.FileBrowse()],      
                 [sg.Submit(), sg.Cancel()]]      
window = sg.Window('Cool Tool Name', window_rows)    
event, values = window.Read()    
window.Close()
source_filename = values[0]    

#written communication term list
dwrit = ('write','written','writing', 'email', 'memo')
written = dwrit

#oral communication term list
doral = ('oral','spoken','talk','speech,')
oral = doral 

#visual communication term list
dvis = ('visual','sight') 
visual = dvis

#auditory communication term list
daud = ('hear', 'hearing', 'heard')
auditory = daud

#multimodal communication term list
dmm = ('multimodal','multi-modal','mixed media','audio and visual')
multimodal = dmm

#define all term lists 
communication = (dwrit, doral, dvis, daud, dmm)

#search lists
from collections import Counter
with open(source_filename, encoding = 'ISO-8859-1') as f:
     for line in f:
         Counter.update(line.lower().split())
print(Counter(communication))

问题是,我现在正在打印 all all 列表中的术语,但我实际上并没有搜索记录那些列出的术语,而忽略所有其他术语...

理想的输出应该是这样的:

书面:[数字、%、单词]

口语:[数字、%、单词]

视觉:[数字,%,单词]

听觉:[数字,百分比,单词]

多模式:[数字、%、单词]

【问题讨论】:

  • 要获取您提到的图表(分布),您可以采用 2 种方式。一种是使用 Graph 元素和线/矩形绘图原语手动绘制图形。另一种是使用 PySimpleGUI 集成的 Matplotlib。
  • 谢谢,@MikeyB!我在实际搜索我拥有的列表(dwrit、doral 等)并在 .txt 文件中仅找到这些术语时遇到了困难。这是我可以输出可视化的第一步。当我使用 print(Counter(communication)) 时,它只会打印所有列表中的所有术语。
  • 查看 PySimpleGUI GitHub 页面上演示文件夹中的示例。它们用 matplotlib 和 pyplot 清楚地标记。

标签: python-3.x nltk


【解决方案1】:

计数器是一个字典,它与您正在计数的事物相联系。这就是为什么您会看到每个单词的原因,您不只是查找与您感兴趣的单词相对应的单词(作为计数器中的键)。下面是一个示例,说明您如何执行其中一项,这是一个可以用来做其他列表的模式。

试试这个:

from collections import Counter
c = Counter()
#search lists
with open(source_filename, encoding = 'ISO-8859-1') as f:
    for line in f:
        c.update(line.lower().split())
written_words = len([x for x in written if x in c.keys()])
print(f'Written: [{written_words}, {written_words/len(c.keys())} %]')

【讨论】:

  • len([x for x in c.keys() if x in written])Counter() 相比,查看written 列表中的单词会更好,因为它默认为0。在大文件上效率更高。
  • 非常感谢@MichaelD!这似乎是一个很好的方法,我可以为其他通信类型设计它,非常漂亮!我收到错误消息:“SyntaxError: f-string: expecting '}'”
  • 抱歉,我在修正之前的错字时放错了 )。
  • @RobertC,如果这是您问题的最佳答案,请将其标记为已回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-17
  • 1970-01-01
相关资源
最近更新 更多