Python文件和文本处理

2024-09-30 12:16:53 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我是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'

我需要的是删除第一首赞美诗,将两个方括号中的每一段文字都标识为一段文字,然后将它们的整体类型标识为方括号中文字后面的圆括号中的内容。 另一件事是,我们可以有一些词不在括号内,应该被忽略

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

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移除赞美诗,但它对我不起作用,当我试着打印阵列时,赞美诗仍然在那里

我希望我的问题是清楚的

提前谢谢大家,


Tags: 文件franktextregovalueaction句子
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)

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

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

现在你可以把这些输入到一个字符串中。(要为所需输出对该字符串集合进行分组,您可以创建一个字符串列表,然后在输出到文件之前按最后一个字对其进行排序)

相关问题 更多 >

    热门问题