0
如果我在一个文件中设置的句子,如:如何根据标签对句子进行分组?
1 let's go shopping
1 what a wonderful day
1 let's party tonight
2 nobody went there
2 it was a deserted place
3 lets go tomorrow
4 what tomorrow
4 ok sure let's see
我想组一组的这些句子。就像所有属于标签'1'的句子应该在一个组中,而在'2'中的那些句子应该在另一个组中。
所以我加载的文件是这样的:
result=[]
with open("sentences.txt","r") as filer:
for line in filer:
result.append(line.strip().split())
,所以我得到这样的:
[['1', 'let's', 'go', 'shopping'],
['1', 'what', 'a', 'wonderful', 'day'],
['1', 'let's', 'party', 'tonight'],
['2', 'nobody', 'went', 'there']]
现在,我想是这样的:
for line in result:
if line[0]== '1':
process(line)
elif line[0]=='2':
process(line)
elif line[0]=='4':
process(line)
elif line[0]=='3':
process(line)
但问题在于它一次只考虑一个句子。我想要一个组中的所有'1',然后对它们运行过程(函数)。
文件1:
[['1', 'in', 'seattle', 'today', 'the', 'secretary', 'of', 'education', 'richard', 'riley', 'delivered', 'his', 'address', 'on', 'the', 'state', 'of', 'american', 'education'], ['1', 'one', 'of', 'the', 'things', 'he', 'focused', 'on', 'as', 'the', 'president', 'had', 'done', 'in', 'his', 'state', 'of', 'the', 'union', 'was', 'the', 'goal', 'to', 'reduce', 'the', 'size', 'of', 'the', 'average', 'class']]
文件2:
[['1', 'in', 'seattl', 'today', 'the', 'secretari', 'of', 'educ', 'richard', 'riley', 'deliv', 'hi', 'address', 'on', 'the', 'state', 'of', 'american', 'educ'], ['1', 'one', 'of', 'the', 'thing', 'he', 'focus', 'on', 'a', 'the', 'presid', 'had', 'done', 'in', 'hi', 'state', 'of', 'the', 'union', 'wa', 'the', 'goal', 'to', 'reduc', 'the', 'size', 'of', 'the', 'averag', 'class']]
你好,请问为什么会出现一个1在line.strip.split('',1)?你是否指的是标签1,如果是的话,我有一些标签,所以它将不得不被修改为每个标签? – minks
@minks不,这里是最大分割时间:https://docs.python.org/2/library/stdtypes.html#str.split – wong2
''ab c'.split('',1) '''a','b c']'结果'ab'.split('',2)'产生'['a','b','c']' – wong2