【问题标题】:Using python for text analytics [closed]使用 python 进行文本分析 [关闭]
【发布时间】:2015-06-10 23:58:54
【问题描述】:

我正在尝试编写一个程序来搜索文本文件中是否包含单词列表。我正在考虑使用两组的交集来实现这一点。我想知道是否有任何其他有效的方法来实现这一目标?

【问题讨论】:

  • 这可能是一个好方法.. 取决于文件的大小

标签: python text text-mining text-extraction


【解决方案1】:

散列也可用于快速查找。

  1. 读取文件并解析文本。

  2. 继续将每个看不见的(新)单词存储在哈希表中。

  3. 最后,检查查找列表中的每个单词是否存在于哈希表中

Python 中的字典是使用哈希表实现的。所以,它可能是一个不错的选择。 这可能是一个入门代码 -

dictionary  = {}
lookup_list = ["word1","word2","word3"]
file_data = []

with open("myfile.txt","r") as f:
    file_data = f.read().split()

for word in file_data:
    if word not in dictionary.keys():
        dictionary[word] = 1
    else:
        dictionary[word] += 1

f.close()

result = [i for i in lookup_list if i in dictionary.keys()]

print result

【讨论】:

    【解决方案2】:

    快速简便的方法

    textblob 是一个文本分析库。

    This part 的文档描述了如何获取单词和名词的频率,例如

    from textblob import TextBlob
    
    >>> monty = TextBlob("We are no longer the Knights who say Ni. "
    ...                     "We are now the Knights who say Ekki ekki ekki PTANG.")
    >>> monty.words.count('ekki', case_sensitive=False)
    3
    

    更高的性能,更慢的方法

    如果您正在寻找高性能并且这是一个大问题,也许可以尝试使用regex 将文件清理到单词列表中,然后使用Collections 获取频率:

    from collections import Counter
    words = ['b','b','the','the','the','c']
    
    print Counter(words)
    Counter({'the': 3, 'b': 2, 'c': 1})
    

    单个查询的更高性能方法

    或者为了单个非重复查询的更高性能(如果您要查询很多单词,请存储为Counter 对象)

    words.count('the')
    3
    

    如果您想要更高的性能,请使用高性能编程语言!

    【讨论】:

      猜你喜欢
      • 2016-07-04
      • 1970-01-01
      • 2018-04-06
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多