Is it possible to extract a string in which a particular word appears more than once in a regular expression?

Asked 2 years ago, Updated 2 years ago, 111 views

Is it possible to extract a string in a regular expression in which a particular word appears more than once?

For example, I would like to extract the string of KW, which appears more than once, as shown in の in the example below.

Example
①Dogs cry a lot.
②The dog in that house is a barking dog.
③That dog ate.

テキスト I would like to know how to use a text editor, but if possible,
It says regular expressions, but I would also like to know examples of automation using python (because I am studying python).

python python3 regular-expression

2022-09-30 21:41

3 Answers

Python automation, but if the search string is fixed and fixed like "dog",
I think filtering using the count method of the string is fast and good.
The count method allows you to count the number of specific strings in a string.
(For example, "abracadabra".count("abra") is 2 when executed.)
Below is the code.

def hantei(s,KW,th):
    returns.count(KW)>=th

strings=["Dogs cry a lot.",
           "The dog in that house is a barking dog.",
           "That dog ate."]

KW = "Dog"
th = 2

filtered_string = [ ]
For s in strings:
    if hantei(s, KW, th):
        filtered_string.append(s)

print(filtered_string)
# Out: ['The dog in that house is a barking dog.']

For your information, you can also write a block of for statements in one line as follows:

filtered_string=[s for strings if hantei(s,KW,th)]


2022-09-30 21:41

"""Dogs"" appear more than once" means ""dogs"" appear at least twice, so you can search by .*dogs.*dogs.*.


2022-09-30 21:41

I'm a beginner, but I just studied Python regular expressions today, so I tried it.

slist=['Dogs cry a lot.', "The dog in that house is a barking dog.', "That dog ate.']
for words in list:
    found=re.findall(".*dog.*dog.*", words)
    for match in found:
        print(match)

I did it with an interpreter, but only the middle sentence was printed as shown below.

>>>The dog in the house is a barking dog.


2022-09-30 21:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.