Questions about re.search, list, counter in Python

Asked 2 years ago, Updated 2 years ago, 12 views

Here's an example of a problem I'm experiencing: a This is an example of extracting words that satisfy the pattern from the list and finding the frequency of those words.

a = ["Weird", "Weird", "Weird", "Weird", "Weird", "Weird"]

p = 'Above' pattern = recompile(p)

for word in a : if pattern.search(word) : Counter(word)

If you enter the command, it doesn't become an overall word count, but for each word Counter ('I:1', 'Sang:1', 'Sun:1') ... ... .. It comes out like this The result I want is

"Weird: 3", "Weird: 1", "Weird: 1". These are the results How can I get the above result?ㅜ<

python

2022-09-21 16:01

1 Answers

if pattern.search(word) : Counter(word)

It's wrong here that' I think you can use it as below!

from collections import Counter
import re

a = ["Weird", "Weird", "Weird", "Weird", "Weird", "Weird"]

p = 'Above'
pattern = re.compile(p)

answer = []
for word in a :
    if pattern.search(word) :
        answer.append(word)
print(Counter(answer))

I created it without changing the logic of the original code as much as possible!


2022-09-21 16:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.