因此,我是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移除赞美诗,但它对我不起作用,当我试着打印阵列时,赞美诗仍然在那里
我希望我的问题是清楚的
提前谢谢大家,
你并不真的需要正则表达式:
只需在括号中拆分字符串:)
现在,您需要插入文件分割线并循环:
当解析像这样的复杂字符串时,使用两阶段方法通常更容易。如果我们首先拆分每个字符串:
为第一个字符串提供一个字符串列表:
现在我们可以编写更简单的正则表达式,从每个子字符串中提取所需的文本:
现在您有两个列表:
将它们压缩在一起,并创建一个新的元组对列表:
看起来是这样的:
现在你可以把这些输入到一个字符串中。(要为所需输出对该字符串集合进行分组,您可以创建一个字符串列表,然后在输出到文件之前按最后一个字对其进行排序)
相关问题 更多 >
编程相关推荐