считать пунктуацию в данном тексте - PullRequest
0 голосов
/ 26 апреля 2019

У меня есть текстовый файл с огромным текстом, написанным в виде абзацев.
Мне нужно сосчитать определенные части знаков препинания: , и ; из этого текста без использования какого-либо модуля, даже regex.
Кроме того, моя программа также должна считать ' и -, но только при определенных обстоятельствах.
В частности, она должна подсчитывать ' отметок, но только тогда, когда они отображаются в виде апострофов, окруженных буквамито есть указание на сокращение, такое как «не должен» или «не будет» .(Апостроф включается в качестве указания на более неформальное письмо, возможно, прямую речь.) Кроме того, он должен считать - знаков, но только тогда, когда они окружены буквами, указывающими составное слово, такое как "самооценка ".

Любые другие знаки препинания или буквы, например цифры, должны рассматриваться как пробел, поэтому служат для завершения слов.
Примечание : Некоторые изТексты, которые мы будем использовать, включают в себя двойной дефис, т.е. --.Это следует рассматривать как пробел.

Сначала я создал строку и сохранил в ней некоторые знаки пунктуации, например punctuation_string = ";./'-", но это дает мне общее количество;то, что мне нужно, это считать индивидуальную пунктуацию.
Из-за этого я должен изменить certain_cha переменное число раз.

with open("/Users/abhishekabhishek/downloads/l.txt") as f:
    text_lis = f.read().split()
punctuation_count = {}
certain_cha = "/"
freq_coun = 0
for word in text_lis:
    for char in word:
       if char in certain_char:
        freq_coun += 1
 punctuation_count[certain_char] = freq_count 

Мне нужно, чтобы значения отображались следующим образом

; 40

. 10

/ 5

' 16

и т. Д.но я получаю всего (71).

Ответы [ 3 ]

1 голос
/ 26 апреля 2019

Вам нужно будет создать словарь, в котором каждая запись будет содержать количество каждого из этих знаков пунктуации.
Для запятых и точек с запятой мы можем просто выполнить поиск строки, чтобы подсчитать количество вхождений в слове.Но нам нужно обработать ' и - немного по-разному.

Это должно позаботиться о всех случаях:

with open("/Users/abhishekabhishek/downloads/l.txt") as f:
    text_words = f.read().split()
punctuation_count = {}
punctuation_count[','] = 0
punctuation_count[';'] = 0
punctuation_count["'"] = 0
punctuation_count['-'] = 0


def search_for_single_quotes(word):
    single_quote = "'"
    search_char_index = word.find(single_quote)
    search_char_count = word.count(single_quote)
    if search_char_index == -1 and search_char_count != 1:
        return
    index_before = search_char_index - 1
    index_after = search_char_index + 1
    # Check if the characters before and after the quote are alphabets,
    # and the alphabet after the quote is the last character of the word.
    # Will detect `won't`, `shouldn't`, but not `ab'cd`, `y'ess`
    if index_before >= 0 and word[index_before].isalpha() and \
            index_after == len(word) - 1 and word[index_after].isalpha():
        punctuation_count[single_quote] += 1


def search_for_hyphens(word):
    hyphen = "-"
    search_char_index = word.find(hyphen)
    if search_char_index == -1:
        return
    index_before = search_char_index - 1
    index_after = search_char_index + 1
    # Check if the character before and after hyphen is an alphabet.
    # You can also change it check for characters as well as numbers
    # depending on your use case.
    if index_before >= 0 and word[index_before].isalpha() and \
            index_after < len(word) and word[index_after].isalpha():
        punctuation_count[hyphen] += 1


for word in text_words:
    for search_char in [',', ';']:
        search_char_count = word.count(search_char)
        punctuation_count[search_char] += search_char_count
    search_for_single_quotes(word)
    search_for_hyphens(word)


print(punctuation_count)
0 голосов
/ 26 апреля 2019

Поскольку вы не хотите что-либо импортировать, это будет медленно и займет некоторое время, но это должно сработать:

file = open() # enter your file path as parameter
lines = file.readline() # enter the number of lines in your document as parameter
search_chars = [',', ';', "'", '-'] # store the values to be searched
search_values = {',':0, ';':0, "'":0, '-':0} # a dictionary saves the number of occurences
whitespaces = [' ', '--', '1', '2', ...] # you can add to this list whatever you need

for line in lines:
    for search in search_chars:
        if search in line and (search in search_chars):
            chars = line.split()
            for ch_index in chars:
                if chars [ch_index] == ',':
                    search_values [','] += 1
                elif chars [ch_index] == ';':
                    search_values [';'] += 1
                elif chars[ch_index] == "'" and not(chars[ch_index-1] in whitespaces) and not(chars[ch_index+1] in whitespaces):
                    search_values ["'"] += 1
                elif chars[ch_index] == "-" and not(chars[ch_index-1] in whitespaces) and not(chars[ch_index+1] in whitespaces):
                    search_values ["-"] += 1

for key in range(search_values.keys()):
    print(str(key) + ': ' + search_values[key])

Это явно не оптимально, и здесь лучше использовать регулярное выражение,но это должно сработать.

Не стесняйтесь спрашивать, если возникнут какие-либо вопросы.

0 голосов
/ 26 апреля 2019

должно работать следующее:

text = open("/Users/abhishekabhishek/downloads/l.txt").read()

text = text.replace("--", " ")

for symbol in "-'":
    text = text.replace(symbol + " ", "")
    text = text.replace(" " + symbol, "")

for symbol in ".,/'-":
    print (symbol, text.count(symbol))
...