The following will read everything into a dictionary keyed by player name. The value associated with each player is itself a dictionary acting as a record with named fields associated with the items converted to a format suitable for further processing.

info = {}
with open('scoring_info.txt') as input_file:
    for line in input_file:
        player, stats, outcome, date = (
            item.strip() for item in line.split('-', 3))
        stats = dict(zip(('kills', 'deaths', 'assists'),
                          map(int, stats.split('/'))))
        date = tuple(map(int, date.split('-')))
        info[player] = dict(zip(('stats', 'outcome', 'date'),
                                (stats, outcome, date)))

print('info:')
for player, record in info.items():
    print('  player %r:' % player)
    for field, value in record.items():
        print('    %s: %s' % (field, value))

# sample usage
player = 'Fizz'
print('\n%s had %s kills in the game' % (player, info[player]['stats']['kills']))

Output:

info:
  player 'Shyvana':
    date: (2012, 11, 22)
    outcome: Loss
    stats: {'assists': 5, 'kills': 12, 'deaths': 4}
  player 'Miss Fortune':
    date: (2012, 11, 22)
    outcome: Win
    stats: {'assists': 3, 'kills': 12, 'deaths': 4}
  player 'Fizz':
    date: (2012, 11, 22)
    outcome: Win
    stats: {'assists': 5, 'kills': 12, 'deaths': 4}

Fizz had 12 kills in the game

Alternatively, rather than holding most of the data in dictionaries, which can make nested-field access a little awkward — info[player]['stats']['kills'] — you could instead use a little more advanced "generic" class to hold them, which will let you write info2[player].stats.kills instead.

To illustrate, here's almost the same thing using a class I've named Struct because it's somewhat like the C language's struct data type:

class Struct(object):
    """ Generic container object """
    def __init__(self, **kwds): # keyword args define attribute names and values
        self.__dict__.update(**kwds)

info2 = {}
with open('scoring_info.txt') as input_file:
    for line in input_file:
        player, stats, outcome, date = (
            item.strip() for item in line.split('-', 3))
        stats = dict(zip(('kills', 'deaths', 'assists'),
                          map(int, stats.split('/'))))
        victory = (outcome.lower() == 'win') # change to boolean T/F
        date = dict(zip(('year','month','day'), map(int, date.split('-'))))
        info2[player] = Struct(champ_name=player, stats=Struct(**stats),
                               victory=victory, date=Struct(**date))
print('info2:')
for rec in info2.values():
    print('  player %r:' % rec.champ_name)
    print('    stats: kills=%s, deaths=%s, assists=%s' % (
          rec.stats.kills, rec.stats.deaths, rec.stats.assists))
    print('    victorious: %s' % rec.victory)
    print('    date: %d-%02d-%02d' % (rec.date.year, rec.date.month, rec.date.day))

# sample usage
player = 'Fizz'
print('\n%s had %s kills in the game' % (player, info2[player].stats.kills))

Output:

info2:
  player 'Shyvana':
    stats: kills=12, deaths=4, assists=5
    victorious: False
    date: 2012-11-22
  player 'Miss Fortune':
    stats: kills=12, deaths=4, assists=3
    victorious: True
    date: 2012-11-22
  player 'Fizz':
    stats: kills=12, deaths=4, assists=5
    victorious: True
    date: 2012-11-22

Fizz had 12 kills in the game
Answer from martineau on Stack Overflow
Top answer
1 of 5
12

The following will read everything into a dictionary keyed by player name. The value associated with each player is itself a dictionary acting as a record with named fields associated with the items converted to a format suitable for further processing.

info = {}
with open('scoring_info.txt') as input_file:
    for line in input_file:
        player, stats, outcome, date = (
            item.strip() for item in line.split('-', 3))
        stats = dict(zip(('kills', 'deaths', 'assists'),
                          map(int, stats.split('/'))))
        date = tuple(map(int, date.split('-')))
        info[player] = dict(zip(('stats', 'outcome', 'date'),
                                (stats, outcome, date)))

print('info:')
for player, record in info.items():
    print('  player %r:' % player)
    for field, value in record.items():
        print('    %s: %s' % (field, value))

# sample usage
player = 'Fizz'
print('\n%s had %s kills in the game' % (player, info[player]['stats']['kills']))

Output:

info:
  player 'Shyvana':
    date: (2012, 11, 22)
    outcome: Loss
    stats: {'assists': 5, 'kills': 12, 'deaths': 4}
  player 'Miss Fortune':
    date: (2012, 11, 22)
    outcome: Win
    stats: {'assists': 3, 'kills': 12, 'deaths': 4}
  player 'Fizz':
    date: (2012, 11, 22)
    outcome: Win
    stats: {'assists': 5, 'kills': 12, 'deaths': 4}

Fizz had 12 kills in the game

Alternatively, rather than holding most of the data in dictionaries, which can make nested-field access a little awkward — info[player]['stats']['kills'] — you could instead use a little more advanced "generic" class to hold them, which will let you write info2[player].stats.kills instead.

To illustrate, here's almost the same thing using a class I've named Struct because it's somewhat like the C language's struct data type:

class Struct(object):
    """ Generic container object """
    def __init__(self, **kwds): # keyword args define attribute names and values
        self.__dict__.update(**kwds)

info2 = {}
with open('scoring_info.txt') as input_file:
    for line in input_file:
        player, stats, outcome, date = (
            item.strip() for item in line.split('-', 3))
        stats = dict(zip(('kills', 'deaths', 'assists'),
                          map(int, stats.split('/'))))
        victory = (outcome.lower() == 'win') # change to boolean T/F
        date = dict(zip(('year','month','day'), map(int, date.split('-'))))
        info2[player] = Struct(champ_name=player, stats=Struct(**stats),
                               victory=victory, date=Struct(**date))
print('info2:')
for rec in info2.values():
    print('  player %r:' % rec.champ_name)
    print('    stats: kills=%s, deaths=%s, assists=%s' % (
          rec.stats.kills, rec.stats.deaths, rec.stats.assists))
    print('    victorious: %s' % rec.victory)
    print('    date: %d-%02d-%02d' % (rec.date.year, rec.date.month, rec.date.day))

# sample usage
player = 'Fizz'
print('\n%s had %s kills in the game' % (player, info2[player].stats.kills))

Output:

info2:
  player 'Shyvana':
    stats: kills=12, deaths=4, assists=5
    victorious: False
    date: 2012-11-22
  player 'Miss Fortune':
    stats: kills=12, deaths=4, assists=3
    victorious: True
    date: 2012-11-22
  player 'Fizz':
    stats: kills=12, deaths=4, assists=5
    victorious: True
    date: 2012-11-22

Fizz had 12 kills in the game
2 of 5
3

You want to use split (' - ') to get the parts, then perhaps again to get the numbers:

for line in yourfile.readlines ():
    data = line.split (' - ')
    nums = [int (x) for x in data[1].split ('/')]

Should get you all the stuff you need in data[] and nums[]. Alternatively, you can use the re module and write a regular expression for it. This doesn't seem complex enough for that, though.

🌐
Computer Hope
computerhope.com › issues › ch001721.htm
How to Extract Specific Portions of a Text File Using Python
June 1, 2025 - In this guide, we'll discuss some simple ways to extract text from a file using the Python 3 programming language. Make sure you're using Python 3. Reading data from a text file. ... Reading text files line-by-line. Storing text data in a variable. Searching text for a substring. Incorporating regular expressions. Putting it all together. Related information...
Discussions

Extract data from text file using Python (or any language) - Stack Overflow
I have a text file that looks like: First Name Bob Last name Smith Phone 555-555-5555 Email bob@bob.com Date of Birth 11/02/1986 Preferred Method of Contact Text Message Desired More on stackoverflow.com
🌐 stackoverflow.com
I need help using python to extract specific data from a text file and put it into an excel file
You probably want to use find or index to locate the specific text (e.g. DDNAME). From there, you can extract whatever portion of the string you need using slicing or more calls to find or index. Check out String Methods from the docs. More on reddit.com
🌐 r/learnpython
10
1
December 30, 2020
python - Extract information from sentence - Data Science Stack Exchange
I'm creating a simple chatbot. I want to obtain the information from the user response. An example scenario: Bot : Hi, what is your name? User: My name is Edwin. I wish to extract the name Edwin f... More on datascience.stackexchange.com
🌐 datascience.stackexchange.com
extracting specific data from a text file in python - Stack Overflow
If I have a text file containing: Proto Local Address Foreign Address State PID TCP 0.0.0.0:11 0.0.0.0:0 LISTENING 12 dns.exe TC... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Medium
medium.com › @gunkurnia › mastering-text-extraction-in-python-a-comprehensive-guide-aa4450254f0e
Mastering Text Extraction in Python: A Comprehensive Guide | by GunKurnia | Medium
December 1, 2024 - “Master text extraction in Python using methods like startswith(), split(), and re.search() for efficient and precise data processing."
🌐
Analytics Vidhya
analyticsvidhya.com › home › hands-on nlp project: a comprehensive guide to information extraction using python
Hands-on NLP Project: A Comprehensive Guide to Information Extraction using Python
October 15, 2024 - Learn about Information Extraction, its process, and tools like SpaCy. Extract insights from text data efficiently with code examples.
🌐
NLTK
nltk.org › book › ch07.html
7. Extracting Information from Text
Typically, these will be definite noun phrases such as the knights who say "ni", or proper names such as Monty Python. In some tasks it is useful to also consider indefinite nouns or noun chunks, such as every student or cats, and these do not necessarily refer to entities in the same way as definite NPs and proper names. Finally, in relation extraction, we search for specific patterns between pairs of entities that occur near one another in the text, and use those patterns to build tuples recording the relationships between the entities.
🌐
Towards Data Science
towardsdatascience.com › home › latest › 3 python modules you should know to extract text data
3 Python Modules You Should Know to Extract Text Data | Towards Data Science
January 29, 2025 - PDF Plumber library is written in python. This library can solve different purposes while extracting text. If we want to extract text or tabular data from any document, this library can be much handy.
Find elsewhere
🌐
Bagustris
bagustris.github.io › nlp-python › 07-ekstrak › index.html
NLP with Python: Extracting information from text
December 24, 2025 - Typically, these will be definite noun phrases such as the knights who say “ni”, or proper names such as Monty Python. In some tasks it is useful to also consider indefinite nouns or noun chunks, such as every student or cats, and these do not necessarily refer to entities in the same way as definite NPs and proper names. Finally, in relation extraction, we search for specific patterns between pairs of entities that occur near one another in the text, and use those patterns to build tuples recording the relationships between the entities.
🌐
GitHub
github.com › google › langextract
GitHub - google/langextract: A Python library for extracting structured information from unstructured text using LLMs with precise source grounding and interactive visualization. · GitHub
LangExtract is a Python library that uses LLMs to extract structured information from unstructured text documents based on user-defined instructions.
Author   google
Top answer
1 of 3
1

first of all you'll need to open the text file in read mode. I'd suggest using a context manager like so:

with open('path/to/your/file.txt', 'r') as file:
    for line in file.readlines():
       # do something with the line (it is a string)

as for managing the info you could build some intermediate structure, for example a dictionary or a list of dictionaries, and then translate that into a CSV file with the csv module.

you could for example split the file whenever there is a blank line, maybe like this:

with open('Downloads/test.txt', 'r') as f:
     my_list = list() # this will be the final list
     entry = dict()   # this contains each user info as a dict
     for line in f.readlines():
         if line.strip() == "":  # if line is empty start a new dict
             my_list.append(entry) # and append the old one to the list
             entry = dict()
         else:                   # otherwise split the line and create new dict
             line_items = line.split(r'  ')
             print(line_items)
             entry[line_items[0]] = line_items[1]
 
 print(my_list)

this code won't work because your text is not formatted in a consistent way: you need to find a way to make the split between "title" and "content" (like "first name" and "bob") in a consistent way. I suggest maybe looking at regex and fixing the txt file by making spacing more consistent.

2 of 3
0

assuming the data resides in a:

a="""
First Name  Bob
Last name   Smith
Phone   555-555-5555
Email   [email protected]
Date of Birth   11/02/1986
Preferred Method of Contact Text Message
Desired Appointment Date    04/29
Desired Appointment Time    10am
City    Pittsburgh
Location    State
IP Address  x.x.x.x
User-Agent (Browser/OS) Apple Safari 14.0.3 / OS X
Referrer    http://www.example.com

First Name  john
Last name   Smith
Phone   555-555-4444
Email   [email protected]
Date of Birth   03/02/1955
Preferred Method of Contact Text Message
Desired Appointment Date    05/22
Desired Appointment Time    9am
City    Pittsburgh
Location    State
IP Address  x.x.x.x
User-Agent (Browser/OS) Apple Safari 14.0.3 / OS X
Referrer    http://www.example.com
"""
line_sep = "\n" # CHANGE ME ACCORDING TO DATA
fields = ["First Name", "Last name", "Phone",
          "Email", "Date of Birth", "Preferred Method of Contact",
          "Desired Appointment Date", "Desired Appointment Time",
          "City", "Location", "IP Address", "User-Agent","Referrer"]
records = a.split(line_sep * 2)
all_records = []
for record in records:
    splitted_record = record.split(line_sep)
    one_record = {}
    csv_record = []
    for f in fields:
        found = False
        for one_field in splitted_record:
            if one_field.startswith(f):
                data = one_field[len(f):].strip()
                one_record[f] = data
                csv_record.append(data)
                found = True
        if not found:
            csv_record.append("")
    all_records.append(";".join(csv_record))

one_record will have the record as dictionary and csv_record will have it as a list of fields (ordered as fields variable)

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-extract-words-from-given-string
Python | Extract words from given string - GeeksforGeeks
July 11, 2025 - When extracting words from a string they offer more accuracy by properly handling punctuation, contractions and tokenization making them ideal for complex or real-world text data. This program demonstrates how to extract words from a string using NLTK's word_tokenize() function. ... import nltk string = "Python is easy-to-learn, powerful and widely used in tech!" words = nltk.word_tokenize(string) print(words)
🌐
Reddit
reddit.com › r/learnpython › i need help using python to extract specific data from a text file and put it into an excel file
r/learnpython on Reddit: I need help using python to extract specific data from a text file and put it into an excel file
December 30, 2020 -

I have been tasked with creating a spreadsheet that shows every a mainframe job accesses a specific application. The application is being retired, and each of the jobs that use it will have to be recoded. I get a daily log file that lists all of the activity in that application, but I need specific items from each of those text blocks exported into a spreadsheet.

Here is a sample block of text from the output:

RECOVERY SUMMARY FOR CDDZD : JOB01513 READER TIME: 0:28:26 READER DATE: 12/29/2020 SMFID: HMP1 0 PGM NAME: SORT DDNAME: SORTOF1 VOLSER: PRD004 DSORG: PS DATA SET: xxx.xxx.xxx.xxx *** TIME OF DAY: 0:30:26 CPU TIME SAVED: 0:00:09 ELAPSE TIME SAVED: 0:01:58 NUMBER OF EXTENTS: 2 *** TYPE OF ATTEMPT: SPACSECI *** SYSLOG MESSAGE: SVM4874I INCREASED SPACE FROM 10 CYLS TO 20

Each daily file has 500-1000 of these blocks.

What I need is a spreadsheet with columns for: PGM NAME, DDNAME, VOLSER, DATA SET, and NUMBER OF EXTENTS. The rest of the data is useless for this project.

The basics of the script I know; opening and reading the file, creating the xls doc, and closing them, etc... But I don't know how to get the info after each data point. I can get output that tells me how many times "PGM NAME" appears in the file, but not the actual program name its listing.

🌐
Medium
medium.com › swlh › python-nlp-tutorial-information-extraction-and-knowledge-graphs-43a2a4c4556c
Python NLP Tutorial: Information Extraction and Knowledge Graphs | by Marius Borcan | The Startup | Medium
May 19, 2021 - This post will be about trying spaCy, one of the most wonderful tools that we have for NLP tasks in Python. Today’s objective is to get us acquainted with spaCy and NLP. We will write some code to build a small knowledge graph that will contain structured information extracted from unstructured text.
🌐
Codementor
codementor.io › community › natural language › information extraction from text using python
Information Extraction from Text Using Python | Codementor
April 22, 2021 - Semi-supervised: When we don’t have enough labeled data, we can use a set of seed examples (triples) to formulate high-precision patterns that can be used to extract more relations from the text. In this section, we will use the very popular NLP library spaCy to discover and extract interesting information from text data such as different entity pairs that are associated with some relation or another.
Top answer
1 of 4
7

You can possibly use a combination of Named Entity Recognition and Syntactical Analysis - while the word Edwin is certainly propping up, imagine a situation where the name is Edward Philip Martel. NER detects each word as a separate entities (hence 3 different entities) - thus, you will anyways have to string them together based on some logic. Further, in the case of multiple names being present, it can get harder to disambiguate (e.g. John & Ramsey dined at Winterfell).

This is where the analysis of the sentence syntax would also help (assuming that the end user enters a relatively coherent and proper sentence - if slang and short forms of text are used, even the Stanford NLP can help upto a certain extent only).

One way of leveraging on syntax analysis / parsing and NER is in the following examples -

 1. User: Edwin is my name.
 2. User: I am Edwin.
 3. User: My name is Edwin.

In each of the cases (as is generically the case as well), the Entity Name (Proper Noun / Noun) is associated in close proximity to a Verb. Hence, if you first parse the sentence to determine verbs and then apply NER to surrounding (+/- 1 or 2) words, you may have a relatively decent way to resolve the problem. This solution would depend primarily on the syntax rules you create to identify NERs as well as the window around the verbs.

2 of 4
5

You should use Named Entity Recognition, for example from NLTK. You can find a usage example here. It would work for your described case quite well.

🌐
Analytics Vidhya
analyticsvidhya.com › home › information extraction using python and spacy
Information Extraction using Python and spaCy - Analytics Vidhya
February 15, 2024 - Hence, the relations extracted from these sentences are: ... Let’s try to implement this technique in Python. We will again use spaCy as it makes it pretty easy to traverse a dependency tree. We will start by taking a look at the dependency tags and POS tags of the words in the sentence: text = "Tableau was recently acquired by Salesforce." doc = nlp(text) for tok in doc: print(tok.text,"-->",tok.dep_,"-->",tok.pos_)
🌐
Medium
medium.com › data-science › how-to-extract-structured-information-from-a-text-through-python-spacy-749b311161e
How to Extract Structured Information from a Text through Python SpaCy | by Angelica Lo Duca | TDS Archive | Medium
June 20, 2021 - I import the en_core_web_sm lexicon, which can be installed through the following command: python -m spacy download en_core_web_sm. The spaCy library supports many languages, whose lexicons can be installed through the same command. Once installed the lexicon, I import it and I load it. Then, I can perform NLP processing. import en_core_web_sm import spacytext = df['text'][0]nlp = en_core_web_sm.load() doc = nlp(text) The doc variable contains all the processed information. In my case, I need only the PoS, which can be extracted as follows:
🌐
Medium
medium.com › john-snow-labs › the-complete-guide-to-information-extraction-from-texts-with-spark-nlp-and-python-c862dd33995f
The Complete Guide to Information Extraction from Texts with Spark NLP and Python | by Gursev Pirge | John Snow Labs | Medium
May 16, 2023 - In this example, we created a BigTextMatcher stage, which matches previously defined person names from the text. Once the Spark NLP pipeline is applied to the sample text, those specified words are extracted. For additional information, please consult the following references:
🌐
O'Reilly
oreilly.com › library › view › natural-language-processing › 9780596803346 › ch07.html
7. Extracting Information from Text - Natural Language Processing with Python [Book]
June 12, 2009 - Chapter 7. Extracting Information from TextFor any given question, it’s likely that someone has written the answer down somewhere. The amount of natural language text that... - Selection from Natural Language Processing with Python [Book]
Authors   Steven BirdEwan Klein
Published   2009
Pages   504