我有這樣一個文件,其中包含句子,標記爲BOS(開始句)和EOS(完句子中):讀取和文件替換考慮到數據從第二個文件
BOS 1
1 word \t\t word \t word \t\t word \t 123
1 word \t\t word \t word \t\t word \t 234
1 word \t\t word \t word \t\t word \t 567
EOS 1
BOS 2
2 word \t\t word \t word \t\t word \t 456
2 word \t\t word \t word \t\t word \t 789
EOS 2
而且第二個文件,其中第一個數字表示語句編號:
1, 123, 567
2, 789
我想是讀第一和第二文件,如果在每行的末尾數字出現在第二個文件進行檢查。如果是這樣,我只想更改第一個文件行中的第四個單詞。因此,預期的輸出結果是:
所有的BOS 1
1 word \t\t word \t word \t\t NEW_WORD \t 123
1 word \t\t word \t word \t\t word \t 234
1 word \t\t word \t word \t\t NEW_WORD \t 567
EOS 1
BOS 2
2 word \t\t word \t word \t\t word \t 456
2 word \t\t word \t word \t\t NEW_WORD \t 789
EOS 2
首先,我不知道如何讀的兩個文件,因爲他們有不同的行數。然後,我不知道如何遍歷行,例如第一個文件中的第一個句子,並同時迭代第二個文件第一行中的值進行比較。這是我到目前爲止:
def readText(filename1, filename2):
data1 = open(filename1).readlines() # the first file
data2 = open(filename2).readlines() # the second one
list2 = [] # a list to store the values of the second file
for line1, line2 in itertools.izip(data1, data2):
l1 = line1.split()
l2 = line2.split(', ')
find = re.findall(r'.*word\t\d\d\d', line1) # find the fourth word in a line, followed by a number
for l in l2:
list2.append(l)
for match in find:
m = match.split() # split the lines of the first file
if (m[0] == list2[0]): # for the same sentence number in the two files
result = re.sub(r'(.*)word\t%s' %m[5], r'\1NEW_WORD\t%s' %m[5],line1)
if len(sys.argv)==3:
lines = readText(sys.argv[1], sys.argv[2])
else:
print("file.py inputfile1 inputfile2")
在此先感謝您的幫助!
請修復您的縮進。並且在輸入文件實際製表符字符中還是'\ t'或只是'\ t'? –
\ t是實際製表符 – isa
什麼是行和句子?是以'\ n'結尾的行還是以'\ n'結尾的句子? –