Python 文件和文本处理

Python file and text processing

所以我是 Python 的新手,我想执行以下操作。

我有一个包含一堆句子的文件,如下所示:

- [frank bora three](noun) [go](action) level [three hundred sixty](value)
- [jack blad four](noun) [stay](action) level [two hundred eleven](value)

我希望能够重现如下所示的文件:

text:'frank bora three', entityType:'noun'
text:'jack blad four', entityType:'noun'   
text:'go', entityType:'action'    
text:'stay', entityType:'action'
text:'three hundred sixty', entityType:'value'
text:'two hundred eleven', entityType:'value'

我需要的是删除第一个 hymph,将两个方括号之间的每个文本标识为文本,然后对于它们的 entityType,它将是我们在方括号之间的文本之后的圆括号之间的内容. 问题是我们可以有一些不在括号中的词,应该被忽略。

方法: 我尝试做的第一件事是将所有句子放在一个数组中:

import re
with open('new_file.txt') as f1:
    lines = f1.readlines()
array_length = len(lines)
for i in range(array_length):
    lines[i]=re.sub(r"\b/-\w+", "", lines[i])
print (lines[0])

在那之后,我尝试使用 re 删除 hymphs,但它对我不起作用,当我尝试打印数组时,hymphs 仍然存在。

我希望我的问题很清楚。

提前谢谢你,

你真的不需要正则表达式:

只是括号之间的字符串分割:)

s = "- [frank bora three]asdasd(noun) [go](action) level [three hundred sixty](value)"

print(s[s.find("[")+1:s.find("]")]) #text inside []
print(s[s.find("(")+1:s.find(")")]) #noun inside ()

现在你需要在你的文件分割线中读取并循环:

stringfile = """- [frank bora three](noun) [go](action) level [three hundred sixty](value)
- [jack blad four](noun) [stay](action) level [two hundred eleven](value)"""


for s in stringfile.splitlines():
    text = s[s.find("[")+1:s.find("]")]
    noun = s[s.find("(")+1:s.find(")")]

    print(text)
    print(noun)

在解析像这样的复杂字符串时,采用两阶段方法通常会更容易。如果我们首先拆分每个字符串:

temp = foo.split(')')[0:3]

给出第一个字符串,一个字符串列表:

temp = ['[frank bora three](noun', ' [go](action', ' level [three hundred sixty](value']

现在我们可以编写更简单的正则表达式来从每个子字符串中提取所需的文本:

re_text = re.compile(r'\[.+\]')
re_entity = re.compile(r'\(.+')
mytext = []
myentitites = []
for target in temp:
     mytext.append(re.search(re_text, target).group().strip('[]'))
     myentities.append(re.search(re_entity, target).group().strip('()'))

现在你有两个列表:

mynouns = ['frank bora three', 'go', 'three hundred sixty']
myentities = ['noun', 'action', 'value']

将它们压缩在一起并制作一个新的元组对列表:

result = list(zip(mynouns, myentities)) #fix

看起来像这样:

[('frank bora three', 'noun'),
 ('go', 'action'),
 ('three hundred sixty', 'value')]

现在您可以将这些输入到字符串中。 (要将此字符串集合分组以获得所需的输出,您可以制作一个字符串列表,然后在输出到文件之前按最后一个单词对其进行排序)