【发布时间】:2015-02-27 19:20:20
【问题描述】:
我有一个 Python 问题,希望得到一些帮助。
让我们从重要的部分开始,这是我当前的代码:
import re #for regex
import numpy as np #for matrix
f1 = open('file-to-analyze.txt','r') #file to analyze
#convert files of words into arrays.
#These words are used to be matched against in the "file-to-analyze"
math = open('sample_math.txt','r')
matharray = list(math.read().split())
math.close()
logic = open('sample_logic.txt','r')
logicarray = list(logic.read().split())
logic.close()
priv = open ('sample_priv.txt','r')
privarray = list(priv.read().split())
priv.close()
... Read in 5 more files and make associated arrays
#convert arrays into dictionaries
math_dict = dict()
math_dict.update(dict.fromkeys(matharray,0))
logic_dict = dict()
logic_dict.update(dict.fromkeys(logicarray,1))
...Make more dictionaries from the arrays (8 total dictionaries - the same number as there are arrays)
#create big dictionary of all keys
word_set = dict(math_dict.items() + logic_dict.items() + priv_dict.items() ... )
statelist = list()
for line in f1:
for word in word_set:
for m in re.finditer(word, line):
print word.value()
该程序的目标是获取一个大文本文件并对其进行分析。本质上,我希望程序循环遍历文本文件并匹配在 Python 词典中找到的单词,并将它们与类别相关联并在列表中跟踪它。
例如,假设我在解析文件时遇到了“ADD”一词。 ADD 列在“数学”或“0”类别的单词下。然后程序应将其添加到它在 0 类别中运行的列表中,然后继续解析该文件。本质上生成一个看起来像 [0,4,6,7,4,3,4,1,2,7,1,2,2,2,4...] 的大列表,每个数字对应一个如上所述的特定状态或类别的单词。为了便于理解,我们将这个大列表称为“statelist”
从我的代码中可以看出,到目前为止,我可以将文件作为输入进行分析,将包含单词列表的文本文件存储到数组中,然后从那里存储到具有正确对应列表值的字典中(a数值从 1 - 7)。但是,我在分析部分遇到了问题。
从我的代码中可以看出,我正在尝试逐行浏览文本文件,并使用字典对找到的任何单词进行正则表达式。这是通过循环和正则表达式完成的,第 9 字典或多或少是一个“超级”字典,以帮助简化解析。
但是,我无法匹配文件中的所有单词,当我找到该单词时,将其与字典值而不是键匹配。那是当它运行并“添加”以将 0 添加到列表中时,因为它是 0 或“数学”类别的一部分。
有人能帮我弄清楚如何编写这个脚本吗?对此,我真的非常感激!很抱歉,这篇文章很长,但代码需要大量解释,所以你知道发生了什么。非常感谢您的帮助!
【问题讨论】:
-
更新:使用此循环打印出单词名称,但不打印类别值。 [for line in f1: for word in word_set: for m in re.finditer(word, line): statelist.append(word)]
-
^对不起,我试图在 cmets 中创建一个代码块,但它不起作用
标签: python regex list parsing dictionary