【问题标题】:Extracting the sentences from one text file from another text file从另一个文本文件中提取一个文本文件中的句子
【发布时间】:2019-01-01 12:42:53
【问题描述】:

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

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)

这次尝试我什么也没得到,实际上是一个空列表。任何建议都会很棒。

【问题讨论】:

  • 你给textfile1中的tags的值为0,tags的格式是什么?或者您也可以共享所需的输出类型。
  • 这是 IOB 标记,唯一可能的标记是 O、B 或 I。我想要的输出是我句子中的单词和标记。我不太关心索引。

标签: python


【解决方案1】:

由于您的第一个文件比第二个文件大得多,因此您希望避免将第一个文件一次全部放入内存中。将第二个文件放入内存是没有问题的。字典将是这种内存的理想数据类型,因为您可以快速找到字典中是否存在单词并快速检索其索引。

所以这样想你的问题——在你的第一个文本文件中找到所有在你的第二个文本文件中的单词。所以这是一个伪代码算法。您没有指定如何完成“输出”,所以我只是笼统地称其为“存储”。您没有说明单词的任何一个“索引”是否要在输出中,所以我把它放在那里。如果你愿意的话,这将是微不足道的。

Initialize a dictionary to empty
for each line in text_file_2:
    parse the index and the word
    Add the word as the key and the index as the value to the dictionary
Initialize the storage for the final result
for each line in text_file_1:
    parse the index, word, and tag
    if the word exists in the dictionary:
        retrieve the index from the dictionary
        store the word, tag, and both indices

这是该算法的代码。为了便于理解和调试,我将其“扩展”而不是使用推导式。

dictfile2 = dict()
with open('txtfile2.txt') as txtfile2:
    for line2 in txtfile2:
        index2, word2 = line2.strip().split()
        dictfile2[word2] = index2
listresult = list()
with open('txtfile1.txt') as txtfile1:
    for line1 in txtfile1:
        index1, word1, tag1 = line1.strip().split()
        if word1 in dictfile2:
            index2 = dictfile2[word1]
            listresult.append((word1, tag1, int(index1), int(index2)))

根据您的示例数据,这是print(listresult) 的代码结果。您可能需要不同的结果格式。

[('effective', 'O', 7, 9)]

【讨论】:

    【解决方案2】:

    @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 出现两次,带有不同的标签,就像它在数据文件中一样。希望这就是您想要的。

    【讨论】:

      【解决方案3】:

      假设文本文件中的间距保持一致

      import re
      
      #open your files
      text_file1 = open('txt file 1.txt', 'r')
      text_file2 = open('txt file 2.txt', 'r')
      #save each line content in a list like l = [[id, word, tag]]
      text_file_1_list = [l.strip('\n') for l in text_file1.readlines()]
      text_file_1_list = [" ".join(re.split("\s+", l, flags=re.UNICODE)).split('') for l in text_file_1_list] 
      #similarly save all the words in text file in list
      text_file_2_list = [l.strip('\n') for l in text_file2.readlines()]
      text_file_2_list = [" ".join(re.split("\s+", l, flags=re.UNICODE)).split(' ')[1] for l in text_file_2_list]
      print(text_file_2_list)  
      # Now just simple search algo btw these two list
      words_found = [[l[1], l[2]] for l in text_file_1_list if l[1] in text_file_2_list]
      print(words_found)
      # [['effective', 'O']]
      

      我认为应该可以。

      【讨论】:

        【解决方案4】:

        您无法找到指定句子的出现次数,因为您在比较时使用句子的索引查看。因此,第二个文件中的一个句子只有在与相同的索引比较时才会出现在第一个文件中

        #file1
        3 make tag
        7 split tag
        
        #file2
        4 make 
        6 split
        

        您以以下方式对它们进行比较if line == part:但显然 4 make 不等于 3 make tag 因为您有 3而不是 4 和另外的 tag 部分 会使条件失败。

        因此,只需更改条件即可检索正确的句子。

        def selectSentence(string):
          """Based on the strings that you have in the example. 
          I assume that the elements are separated by one space char
          and that in the sentences aren't spaces"""
          elements = string.split(" ")
          return elements[1].strip()
        
        txtfile1 = open("file1.txt").read().split('\n')
        with open ('file2.txt','r') as txtfile2:
        
           whatineed=[]
           for line in txtfile2:
               for part in txtfile1:
                 if selectSentence(line) == selectSentence(part): 
                    whatineed.append(part)
        
        print(whatineed)
        

        我的方法

        就像@Rory Daulton 一样,您的文件非常大,因此将其全部加载到内存中是个坏主意。一个更好的想法是迭代它,同时您可以存储小文件(第二个)所需的数据。

        txtfile2 = open("file2.txt").read().split('\n')
        sentences_inf2 = {selectSentence(line) for line in txtfile2} #set to remove duplicates
        with open ('file1.txt','r') as txtfile1:
        
           whatineed=[]
           for line in txtfile1:
                 if selectSentence(line) in sentences_inf2: 
                    whatineed.append(line.strip())
        
        print(whatineed) #['7 effective O']
        

        【讨论】:

          猜你喜欢
          • 2021-11-01
          • 1970-01-01
          • 2019-03-06
          • 1970-01-01
          • 1970-01-01
          • 2018-03-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多