Home > Back-end >  How to extarct text from file with id?
How to extarct text from file with id?

Time:05-16

i have two files. one contains id and the other contains sentences for each id but with little changes like this example

File1 :

111_3232
111_ewe2
111_3434
222_3843h
222_39092

File2 :

111   some_text_1   some_text_1
222   some_text_2  some_text_2

i need to make a file with id and its sentences like

111_3232   some_text_1   some_text_1
111_ewe2   some_text_1   some_text_1
111_3434   some_text_1   some_text_1
222_3843h  some_text_2  some_text_2
222_39092  some_text_2  some_text_2

I tried this code

import os 

f = open("id","r")
ff = open("result","w")
fff = open("sentences.txt","r")
List = fff.readlines()    
i =0 
for line_id in f.readlines():
    for line_sentence in range(len(List)):
        if line_id in List[i]:
            ff.write(line_sentence)
        else : 
            i =1

but got

if line_id in List[i]:
IndexError: list index out of range

as I got the whole line from file2, not id only... is there any way better than i make

EDIT

i tried to use panads but I'm not familiar with it well by this code

df = pd.read_csv('sentence.csv')    
for line_id in f.readline():
    for line_2 in df.iloc[:, 0] :
       for (idx, row) in df.iterrows():
            if line_id in line_2:
                ff.write(str(row)  '\n')
            else : 
                ff.write("empty"  '\n')

but got the wrong data as I couldn't catch the right row well

CodePudding user response:

One way of achieving the result is to store the sentences and file_id pair in a dictionary and iterate over the id file content to get the result

sentences_dict = {}
# read all sentences into a dictionary as key value pair
with open("sentences.txt", "r") as sentences_file:
    for line in sentences_file.read().splitlines():
        split_lines = line.split(" ")
        sentences_dict.update({split_lines[0].strip():  "  ".join(split_lines[1:])})

result_file = open("result.txt", "w")

# iterate over id file and match the starting text
with open("id.txt", "r") as id_file:
    for file_id in id_file.read().splitlines():
        txt = sentences_dict.get(file_id.split("_")[0], "")
        result_file.write(f"{file_id}{txt}\n")
        
result_file.close()

Make sure to always close a file explicitly unless you are opening along with the with keyword.

CodePudding user response:

A basic approach

with open('file1.txt', 'r') as fd1, open('file2.txt', 'r') as fd2:
    lines1 = fd1.read().split() # remove \n
    lines2 = fd2.readlines()

new_text = ''
for l1 in lines1:
    for id_, t1, t2 in (l.split() for l in lines2):
        if l1.startswith(id_):
            new_text  = f'{l1} {t1} {t2}\n'

with open('file3.txt', 'w') as fd:
    fd.write(new_text.strip())
  • Related