Найти специальные символы, где я встречаюсь чаще всего - PullRequest
0 голосов
/ 30 октября 2018

У меня есть задание, в котором мне нужно посчитать специальные символы в строке, где это происходит чаще всего.

Файл, который у меня есть, содержит три абзаца с текстом, и мне нужно сравнить их друг с другом, чтобы увидеть, где происходит набор символов, а затем подсчитать их там, где они встречаются чаще всего.

Строки в тексте: 'I cannot go now. Give me lunch first at 12:15.'

After 13:100, he took a nap for until 13:15. Then in the late afternoon on 2018-11:30 at 16:30, he picked some bags and went to the palace. On the way, he felt hot so he sat under a tree to rest. Then, two hours later at 18:30, he got up to go but saw a man showing some magic tricks. He stopped to watch for an until 21:04.

When he reached the palace it was already after 21:03. The palace gates had been shut. So Haria had lost a golden chance because he had not learned the value of time on the 2018-13-01, a beautiful day.

Код, который у меня пока есть:

number_of_specials = 0
c = ['.', '.', ';', ':', '!', '?']
top = []
top_c1 = 0
top_c2 = 0
top_c3 = 0

with open(TEXT, "r") as fh:
    for line in fh:
        top.append(line.split("\n")) //to get the lines

if c in top[0]:
    top_c1 += 1

Не уверен, куда идти отсюда, приветствуются любые указатели

Ответы [ 2 ]

0 голосов
/ 30 октября 2018

Вы можете сохранить строку и количество вхождений в кортеже, а также увеличить значение вхождений по количеству определенного символа в строке (строке).

class Counter(object): # mutable object is needed to access it from tuple
    def __init__(self, start_value=0):
        self.value = start_value

    def __str__(self):
        return str(self.value)

c = ['.', '.', ';', ':', '!', '?']
top = []

with open(TEXT, "r") as fh:
    for line in fh:
        top.append((line.split("\n"), Counter(0)))

for line, occurrences in top:
    for character in c:
        occurrences.value += line.count(character)
0 голосов
/ 30 октября 2018

Попробуйте это:

import re
c = ['.', '.', ';', ':', '!', '?']
top = ['asdd..,;;.:']
top_len = len(re.findall('['+''.join(c)+']',top[0]))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...