【问题标题】:Python file and text processingPython文件和文本处理
【发布时间】:2020-06-21 11:18:10
【问题描述】:

所以我是 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'

我需要删除第一个连字符,将两个方括号之间的每个文本标识为文本,然后对于它们的 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 删除 hymph,但它对我不起作用,当我尝试打印数组时,hymph 仍然存在。

我希望我的问题很清楚。

提前谢谢你,

【问题讨论】:

  • 请发布您尝试过的重新代码,以及它以何种方式不起作用。这是您问题的真正症结所在。
  • 通过编辑您的问题添加此重要信息 - 人们并不总是扫描 cmets 以获取更多信息。
  • 好的,谢谢。

标签: python python-textprocessing


【解决方案1】:

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

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

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

【讨论】:

  • 刚刚注意到我在那个 list(zip) 语句中有一个错字,现在已修复
【解决方案2】:

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

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

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)

【讨论】:

  • 感谢您的回答,我接受了另一个,因为在我的示例中,除了名词(动作、值..)之外还有实体,但它仍然是问题的答案。
猜你喜欢
  • 2017-06-18
  • 1970-01-01
  • 2016-04-19
  • 1970-01-01
  • 2016-09-02
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
  • 2014-06-23
相关资源
最近更新 更多