#python #list
Вопрос:
Как я могу извлечь идентификатор, который следует за строкой » worldandplaces/обзор мест/», и сохранить в отдельном списке python? Идентификатор не всегда присутствует для каждого элемента в списке. И если есть элемент без идентификатора, я хотел бы добавить его также в новый список как «нет».
Мои усилия до сих пор:
myString =[" --------------- userLang: en-us refUrl: worldandplaces/place-review/12345-6789-d1e2-4444-907e555ce5d5 Email address: johndoe@gmail.com", " --------------- userLang: en-us refUrl: worldandplaces/place-review/09876-5432-c3d3-9999-307e555ce665 Email address: janedoe@gmail.com", "------ userLang: en-us refUrl: worldandplaces/ Email address: janedoe@gmail.com"]
placeID =[]
for entry in myString:
try:
placeID.extend([f for f in entry.split(' ') if f.startswith('worldandplaces')])
except:
placeID.append('none')
Текущий результат:
['worldandplaces/place-review/12345-6789-d1e2-4444-907e555ce5d5', 'worldandplaces/place-review/09876-5432-c3d3-9999-307e555ce665']
Ожидаемый результат:
['12345-6789-d1e2-4444-907e555ce5d5', '09876-5432-c3d3-9999-307e555ce665', 'none']
Комментарии:
1.
if f.startswith(...)
, он добавит элемент только в том случае, если строка начинается сworldandplaces
Ответ №1:
Вы можете просто узнать, где worldandplaces/place-review/
находится префикс, и после этого выбрать идентификатор:
myString = [" --------------- userLang: en-us refUrl: worldandplaces/place-review/12345-6789-d1e2-4444-907e555ce5d5 Email address: johndoe@gmail.com", " --------------- userLang: en-us refUrl: worldandplaces/place-review/09876-5432-c3d3-9999-307e555ce665 Email address: janedoe@gmail.com", "------ userLang: en-us refUrl: worldandplaces/ Email address: janedoe@gmail.com"]
placeID = []
target = 'worldandplaces/place-review/'
lentarget = len(target)
for entry in myString:
try:
idx = entry.index(target) lentarget
substr = entry[idx:]
placeID.append(substr.split(' ')[0])
except Exception as e:
placeID.append('none')
print(placeID)
Вывод по запросу.
Ответ №2:
Это даст необходимый результат.
myString = [
" --------------- userLang: en-us refUrl: worldandplaces/place-review/12345-6789-d1e2-4444-907e555ce5d5 Email address: johndoe@gmail.com",
" --------------- userLang: en-us refUrl: worldandplaces/place-review/09876-5432-c3d3-9999-307e555ce665 Email address: janedoe@gmail.com",
"------ userLang: en-us refUrl: worldandplaces/ Email address: janedoe@gmail.com",
]
placeID = []
for entry in myString:
try:
placeID.extend(
[f.split("/")[2] for f in entry.split(" ") if f.startswith("worldandplaces")]
)
except IndexError:
placeID.append('none')
print(placeID)
OUTPUT
['12345-6789-d1e2-4444-907e555ce5d5', '09876-5432-c3d3-9999-307e555ce665', 'none']
Комментарии:
1. Вы проверили код:
IndexError: list index out of range
2. Упс, по какой-то причине я опубликовал сообщение без блока «Попробовать/кроме».
Ответ №3:
Простое решение с использованием регулярного выражения re.findall
import re
myString = [
" --------------- userLang: en-us refUrl: worldandplaces/place-review/12345-6789-d1e2-4444-907e555ce5d5 Email address: johndoe@gmail.com",
" --------------- userLang: en-us refUrl: worldandplaces/place-review/09876-5432-c3d3-9999-307e555ce665 Email address: janedoe@gmail.com",
"------ userLang: en-us refUrl: worldandplaces/ Email address: janedoe@gmail.com",
]
placeID = []
for entry in myString:
# Option 1: If an entry can contain multiple occurrences
occurrences = re.findall(r"worldandplaces/place-review/([S]*)", entry)
placeID.extend(occurrences or ['none'])
# Option 2: If an entry only has 1 occurrence
# occurrence = re.search(r"worldandplaces/place-review/([S]*)", entry)
# placeID.append(occurrence.group(1) if occurrence else 'none')
print(placeID)
Выход
['12345-6789-d1e2-4444-907e555ce5d5', '09876-5432-c3d3-9999-307e555ce665', 'none']