Home>

Detect"my name is"from a text sentence like the following,
Immediately after (same line)"[familyname] xxxx, [givenname] xxxxx"
I want to get a string like
* The character string is appropriate. I'm sorry.
I want to be able to handle even complex things
I posted here.

# text.txt
year = 2018, month = 08
typhoon is coming !!
my nAme IS cactus hahaha
abcdefghijklmn
my name is [familyname] power, [givenname] point
sunny yeah happy happy happy
my name is [familyname] !!!, [givenname] ????
Problems i am experiencing

You can read text files yourself,
You will not be able to find out if the content is a little difficult.

Applicable source code

However, there is code that came up.

#Read one character at a time.
In the #while statement,
Find if m:
 Find if y:
  Find if "":
...


Find my name is as
Then the string I want is on the same line (no unnecessary elements)
It seems to be okay to use readline ().

Supplemental information (FW/tool version etc.)

windows10, VScode, anaconda,

  • Answer # 1

    It is a little cumbersome to solve this kind of problem forcibly, and the use of regular expressions will be considered.

    import re
    with open ('text.txt') as fin:
        data = fin.read ()
    for m in re.findall (r '^ my name is (. +) $', data, re.MULTILINE):
        print (m)

    ResultsWandbox

    [familyname] power, [givenname] point
    [familyname] !!!, [givenname] ????

    Let's learn a little from this opportunity.

    or

    If you don't mind a low degree of freedom, you can use str.startswith.
    However, if the problem becomes even a little complicated, it cannot be dealt with.

    with open ('text.txt') as fin:
        data = fin.read ()
    for line in data.split ('\ n'):
        if not line.startswith ('my name is'):
            continue
        print (
            line [len ('my name is'):]
        )

    ResultsWandbox

    [familyname] power, [givenname] point
    [familyname] !!!, [givenname] ????