简体   繁体   中英

find a word in the sentences and replace whole sentence with a number

I'm a beginner. I have 757 rows with a different statement. I would like to write a command to find the statement with "e-bike" and replace it with the number 1: 1st statement : "a conflict between cyclists and pedestrians, a conflict between two cyclists, a conflict between e-biker and a cyclist" 2nd statement: "a conflict relating to a dog(s), a conflict between cyclists and pedestrians, a conflict between an e-biker and a pedestrian, a conflict between e-biker and a cyclist" If I want to replace one by one I have to write the 757 command.

Thanks

Elham

You can use .replace('<old_string>', '<new_string>') while iterating through your rows.

def replace_rows(rows)
    for i in range(len(rows)):
        rows[i] = rows[i].replace('e-bike', '1')

    return rows

Or even with list comprehension:

def replace_rows(rows):
    return [i.replace('e-bike', '1') for i in rows]

You may try something like, assuming you have a list of sentences sentences_list :

results = []

for sentence in sentences_list:
    results.append(sentence.replace("e-bike", "1"))

print(results)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM