AHAD
AHAD

Reputation: 239

Read text file lines based on a specific format

Hi i have a text file contain many lines such as follows:


224:

و أما أبو حلوه فكان له قدر و مات بالبصرة.

 Trigger: مات  Victim:أبو حلوه ,  Agent:,  Place: البصرة ,  Time:  

225:

بن زيد بن أصرم بن زيد بن ثعلبة بن غنم و أمه عمرة بنت مسعود بن قيس بن عمرو بن زيد. و شهد بدرا واحدا و الخندق و المشاهد كلها مع رسول الله. ص. و توفي في خلافة عثمان بن عفان. رضي الله عنه. و ليس له عقب

 Trigger: توفي  Victim: رضي الله ,  Agent:,  Place:,  Time: في خلافة عثمان بن عفان

226:

و أخذت شيئا، فضربت به، فشجته. فقام ذليلا. فو الله ما عاش إلا سبع ليال، حتى رماه الله بالعدسة، فقتلته. و لقد ترك حتى أنتن. و عذل ابناه في ذلك،(چاپ‏زكار،ج‏2،ص:120) فصبا عليه الماء و ما مساه، و دفن بأعلى مكة إلى جدار، و قذفوا عليه الحجارة حتى واروه بها. و مات أبو رافع بعد خلافة ع

 Trigger: قتلته  Victim:مرجع ضمير متصل به قتلته(الله ),  Agent:,  Place:العدسة,  Time:بعد  خلافة    226:Trigger: دفن,  Victim:,  Agent:,  Place:أعلي,  Time:بعد  خلافة      226:Trigger: مات,  Victim:أبو رافع ,  Agent:,  Place:,  Time:بعد  خلافة  

and i want to read this text file and encode it to a csv file with these columns:

text, Trigger, Victim, Agent, Place, Time

i try the following code:

text_file = open("myfile.txt", "r")
lines = text_file.readlines()
desired_lines = lines[1::4]
desired_lines2 = lines[3::4]
for l in desired_lines:
    print l
for l2 in desired_lines2:
    print l2

but it doesn't return the appropriate result.

Upvotes: 0

Views: 58

Answers (1)

madjaoue
madjaoue

Reputation: 5224

What you're trying to achieve is a bit more complicated that just getting the lines. Especially with your CSV format that seems really inconsistant.

I implemented a "dummy" parser with regex, this should give you a pretty solid base for the rest of your file :

import re
from collections import defaultdict

result = defaultdict(dict)

with open('a.txt', 'r') as f:
    for line in filter(None, (line.rstrip() for line in f)):
        if len(line) and re.search(r'^[0-9]+(:)', line):  # detect "225:" like patterns
            new_section = True
            current_id = line.split(':')[0]
            print('id : {}'.format(current_id))
            continue

        elif new_section:
            result[current_id]['text'] = line
            print("text : {}".format(line))
            new_section = False
        else:
            mappings = filter(None, (line.rstrip() for line in line.split(',')))
            first_mapping = mappings[0]

            # match the substring until V letter
            p = re.compile("^(.*)V")
            trigger_str = p.search(first_mapping).group(1)

            # get the remaining part of the stirng
            value_str = first_mapping[len(trigger_str):]
            mappings = [trigger_str, value_str] + mappings[1:]

            for mapping in mappings:
                key, value = mapping.split(':')[:2]
                print('{}: {}'.format(key, value))
                result[current_id][key] = value

print result

Output :

id : 224
text : و أما أبو حلوه فكان له قدر و مات بالبصرة.
Trigger:  مات  
Victim: أبو حلوه
  Agent: 
  Place:  البصرة
  Time: 
id : 225
text : بن زيد بن أصرم بن زيد بن ثعلبة بن غنم و أمه عمرة بنت مسعود بن قيس بن عمرو بن زيد. و شهد بدرا واحدا و الخندق و المشاهد كلها مع رسول الله. ص. و توفي في خلافة عثمان بن عفان. رضي الله عنه. و ليس له عقب
Trigger:  توفي  
Victim:  رضي الله
  Agent: 
  Place: 
  Time:  في خلافة عثمان بن عفان
id : 226
text : و أخذت شيئا، فضربت به، فشجته. فقام ذليلا. فو الله ما عاش إلا سبع ليال، حتى رماه الله بالعدسة، فقتلته. و لقد ترك حتى أنتن. و عذل ابناه في ذلك،(چاپ‏زكار،ج‏2،ص:120) فصبا عليه الماء و ما مساه، و دفن بأعلى مكة إلى جدار، و قذفوا عليه الحجارة حتى واروه بها. و مات أبو رافع بعد خلافة ع
Trigger:  قتلته  
Victim: مرجع ضمير متصل به قتلته(الله )
  Agent: 
  Place: العدسة
  Time: بعد  خلافة

Upvotes: 1

Related Questions