gpt4 book ai didi

python - 从一个文本文件中提取另一个文本文件中的句子

转载 作者:太空宇宙 更新时间:2023-11-04 02:09:09 25 4
gpt4 key购买 nike

我有两个 txt 文件,一个非常大(txt 文件 1),有 15000 个句子,每行都以一组格式(句子索引、单词、标签)​​分解。我有另一个文本文件(txt 文件 2),其中大约 500 个句子被分解成格式(句子索引,单词)。我想从“txt 文件 1”中找到“txt 文件 2”中的句子,但我还需要提取标签。

txt 文件 1 的格式:

1   Flurazepam  O
2 thus O
3 appears O
4 to O
5 be O
6 an O
7 effective O
8 hypnotic O
9 drug O
10 with O

txt文件2的格式:

1   More
2 importantly
3 ,
4 this
5 fusion
6 converted
7 a
8 less
9 effective
10 vaccine

最初,我只是尝试了一些愚蠢的事情:

txtfile1=open("/Users/Desktop/Final.txt").read().split('\n')


with open ('/Users/Desktop/sentenceineed.txt','r') as txtfile2:

whatineed=[]
for line in txtfile2:
for part in txtfile1:
if line == part:
whatineed.append(part)

这次尝试我一无所获,实际上是一个空列表。任何建议都会很棒。

最佳答案

@Rory Daulton 正确地指出了这一点。由于您的第一个文件可能大到足以将其完全加载到内存中,因此您应该迭代它。

我在这里写下我的解决方案。您可以为您的实现做出必要/所需的更改。

程序

dict_one = {} # Creating empty dictionary for Second File
textfile2 = open('textfile2', 'r')

# Reading textfile2 line by line and adding index and word to dictionary
for line in textfile2:
values = line.split(' ')
dict_one[values[0].strip()] = values[1].strip()

textfile2.close()

outfile = open('output', 'w') # Opening file for output
textfile1 = open('textfile1', 'r') # Opening first file

# Reading first file line by line
for line in textfile1:
values = line.split(' ')
word = values[1].strip() # Extracting word from the line

# Matching if word exists in dictionary
if word in dict_one.values():
# If word exists then writing index, word and tag to the output file
outfile.write("{} {} {}\n".format(values[0].strip(), values[1].strip(), values [2].strip()))

outfile.close()
textfile1.close()

文本文件 1

1 Flurazepam O
2 thus O
3 appears I
4 to O
5 be O
6 an O
7 effective B
8 hypnotic B
9 drug O
10 less O
11 converted I
12 maxis O
13 fusion I
14 grave O
15 public O
16 mob I
17 havoc I
18 boss O
19 less B
20 diggy I

文本文件 2

1 More
2 importantly
3 ,
4 this
5 fusion
6 converted
7 a
8 less
9 effective
10 vaccine

输出文件

7 effective B
10 less O
11 converted I
13 fusion I
19 less B

在这里,less与在数据文件中一样使用不同的标 checkout 现两次。希望这就是您要找的。

关于python - 从一个文本文件中提取另一个文本文件中的句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53995522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com