#python #word #capitalize
Вопрос:
Как указать слова, начинающиеся с заглавной буквы, и номер этого слова в тексте? Если в тексте не найдено слово с этим атрибутом, выведите его в выводе «Нет». Слова в начале предложения не следует рассматривать. Числа не следует учитывать, и если точка с запятой находится в конце слова, эту точку с запятой следует опустить.
Как в следующем примере:
Ввод:
The University of Edinburgh is a public research university in Edinburgh, Scotland. The University of Texas was included in the Association of American Universities in 1929.
Выход:
2:University 4:Edinburgh 11:Edinburgh 12:Scotland 14:University 16:Texas 21:Association 23:American 24:Universities
Ответ №1:
Слова в начале предложения не следует рассматривать
Это усложняет процесс, потому что сначала вы должны определить, как разделяется предложение. предложение может заканчиваться знаками препинания, например . or ! or ?
. Но вы не завершили последнее предложение в своем примере полной остановкой. для этого ваш корпус должен быть предварительно обработан!
Отложив этот вопрос в сторону, предположим, что этот сценарий:
import re inp = "The University of Edinburgh is a public research university in Edinburgh, Scotland. The University of Texas was included in the Association of American Universities in 1929! The last Sentence." sentences = re.findall(r"[ws,]*[.!?]",inp) counter = 0 for sentence in sentences: sentence = re.sub(r"W", " ",sentence) sentence = re.sub(r"s ", " ", sentence) words = re.split(r"s", sentence) words = [w for w in words if w!=""] for i, word in enumerate(words): if word != "" and i != 0: if re.search(r"[A-Z] ", word): print("%d:%s" % (counter i 1, word)) counter = len(words)
Этот код-именно то, что вам нужно. Это не лучшая практика, но это жесткий и простой код. Обратите внимание, что сначала вам нужно указать знаки препинания в конце каждого предложения для входного предложения!!!
Вывод:
2:University 4:Edinburgh 11:Edinburgh 12:Scotland 14:University 16:Texas 21:Association 23:American 24:Universities 29:Sentence
Комментарии:
1. Большое спасибо. Твой код был идеален.
2. @M_92 Если это было полезно, пожалуйста, проголосуйте за мой ответ и отметьте его как ответ :)))))
Ответ №2:
Вот код. Вы можете добавить любой другой символ в раздел, и он должен удалить его из конца слова. Вы также можете изменить последнюю печать на все, что захотите.
import numpy as np s1="The University of Edinburgh is a public research university in Edinburgh, Scotland. The University of Texas was included in the Association of American Universities in 1929." n = [] for index, word in enumerate(s1.split()): if word[0].isupper(): if string[index-1][-1] == ".": #check that previous word does not end in a ".". continue print(f"""{index 1}:{word.strip(",.;:")}""") #python index is one number lower, so add one to it to get the numbers you requested n.append(word) #this is just to be able to print something if no words have capital letters if len(n) == 0: print("None")
Ответ №3:
Попробуйте этот код
Просто вам нужно использовать .istitle()
метод в строке, чтобы проверить, начинается ли она с заглавной буквы, а остальные — в нижнем регистре
И используя регулярное выражение, вы можете удалить слово, исключая символы в конце (при условии, что вы не хотите включать символы, как вы упомянули, чтобы игнорировать точку с запятой в конце слова).
import re inp = 'The University; of Edinburgh is a public research university in Edinburgh, Scotland. The University of Texas was included in the Association of American Universities in 1929' inp2 = '' def capitalized_words_in_a_text(inp): lst = inp.split(' ')[1:] res = [f"{i}: {re.match(r'^[A-Za-z] ', j).group()}" for i,j in enumerate(lst, start=2) if j.istitle()] if len(res) == 0: return return 'n'.join(res) print(capitalized_words_in_a_text(inp)) print(capitalized_words_in_a_text(inp.lower()))
Выходы:
2: University 4: Edinburgh 11: Edinburgh 12: Scotland 13: The 14: University 16: Texas 21: Association 23: American 24: Universities None # this is from the inp.lower() line, as there's no capital letters in the string
Скажи мне, если это не сработает…