Я беру свої перші кроки до Python, і у мене є проблема для вирішення, в якій мені потрібен регулярний вираз.
Я аналізую кілька рядків тексту, і мені треба схопити 5 слів до і після певного матчу. Термін "матч" завжди однаковий, і лінії можуть мати більше ніж одну появу цього терміну.
r"(?i)((?:S+s+){0,5})<tag>(w*)</tag>s*((?:S+s+){0,5})"
Це працює у дуже специфічних ситуаціях: якщо існує лише одна особливість терміна між тегами (або якщо вони знаходяться на відстані між ними), і якщо до першої події є достатньо слів.
Проблема в тому, що:
1 - якщо другий випадок знаходиться в межах діапазону +5 першої події, для другої не існує -5, або другий просто поглинається першим. Перехресне завдання?
2 - якщо є менше 5 слів, або якщо ви досягли діапазону до 7 або 8, він просто пропускає перше входження до другого або третього.
Отже, лінія, що має щось на кшталт:
word word word match word word match word word word
Не буде добре розібратися.
Чи є спосіб врахувати ці питання та зробити його роботою?
Дякую всім заздалегідь!
Відповіді:
1 для відповіді № 1Це може бути те, що ви після - без використання регулярного виразу
#!/usr/bin/env python
def find_words(s, count, needle):
# split the string into a list
lst = s.split()
# get the index of the where the needle is
idx = lst.index(needle)
# s is the start and end of the list you need
s = idx -count
e = idx +count
# print the list as slice notation
print lst[s:e+1]
def find_occurrences_in_list(s, count, needle):
# split the string into a list
lst = s.split()
idxList = [i for i, x in enumerate(lst) if x == needle]
# print idxList
r = []
for n in idxList:
s = n-count
e = n+count
# append the list as slice notation
r.append(" ".join(lst[s:e+1]))
print r
# the string of words
mystring1 = "zero one two three four five match six seven eight nine ten eleven"
# call function to find string, 5 words head & behind, looking for the word "match"
find_occurrences_in_list(mystring1, 5, "match")
# call function to find string, 3 words head & behind, looking for the word "nation"
mystring2 = "Four score and seven years ago our fathers brought forth on this continent a new nation conceived in Liberty and dedicated to the proposition"
find_occurrences_in_list(mystring2, 3, "nation")
mystring3 = "zero one two three four five match six seven match eight nine ten eleven"
find_occurrences_in_list(mystring3, 2, "match")
["one two three four five match six seven eight nine ten"]
["continent a new nation conceived in Liberty"]
["four five match six seven", "six seven match eight nine"]