Python разбирает определенные слова из текста - PullRequest
0 голосов
/ 12 октября 2019

Я хочу подсчитать конкретные упоминания слова «кровь» в тексте, но я не очень далеко продвинулся. Я перепробовал несколько вещей, и самое большее, что я получил, это возможность разобрать все предложения, содержащие слово. это то, что я имею до сих пор, который заканчивается с кодом выхода 0

 infile = open('C:\IS452\week7\dracula.txt', 'rt', encoding = 'utf=8')
    dracula_lines = infile.readlines()
    infile.close()

    for blood_lines in dracula_lines:

    accumulator = blood_lines.strip()


    dracula_lines.count("blood")
    if "blood" in dracula_lines:
        print("blood") in str(newText[blood_lines + 1])
    #print(blood_lines)

    blood_lines = accumulator.split("blood")
    newText = ("There are this many mentions of blood in Dracula", blood_lines)
      print(newText)

1 Ответ

0 голосов
/ 12 октября 2019

Вы можете просто использовать .count () непосредственно в строке:

with open('C:\IS452\week7\dracula.txt', 'r', encoding = 'utf=8') as f:
  dracula_txt = f.read().lower()

blood_count = dracula_txt.count("blood")
print(blood_count, "mentions of blood in Dracula")

Если вы делаете это для какой-то задачи кодирования, когда вам не разрешено просто использовать .count(), тогда, возможно, вы можете сделать что-то вроде:

dracula_list = dracula_txt.split("blood") # split text into list separated by occurrences of "blood"
blood_count = len(dracula_list) - 1 # count of occurrences is the length of the list minus one

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

index = blood_count = 0
while(index != -1):
  try:
    # we get the position of the next occurrence of "blood" in the string, starting from the position of the last occurrence plus one
    index = dracula_txt.index("blood", index) + 1
    blood_count += 1
  except ValueError: # when there aren't any more occurrences of "blood" in the string, we get a ValueError and exit the loop 
    index = -1
print(blood_count, "mentions of blood in Dracula")

Или вы можете перебиратькаждый символ в строке, проверяя, соответствует ли подстрока, следующая за индексом символа, «кровью» и, соответственно, увеличивая счетчик:

blood_count = 0
for i in range(0, len(dracula_txt)):
    if dracula_txt[i:i+5] == "blood":
        blood_count += 1
print(blood_count)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...