簡體   English   中英

將字符串解析為 Python 中的不同格式

[英]Parsing the String to different format in Python

我有一個文本文檔,我需要在數組中的關鍵字之前添加兩個 @ 符號。

示例文本和數組:

str ="This is a sample text document which consists of all demographic information of employee here is the value you may need,name: George employee_id:14296blood_group:b positive this is the blood group of the employeeage:32"

arr=['name','employee_id','blood_group','age']

所需文字:

str ="This is a sample text document which consists of all demographic information of employee here is the value you may need, @@name: George @@employee_id:14296 @@blood_group:b positive this is the blood group of the employee @@age:32"

只需使用replace function

str ="This is a sample text document which consists of all demographic information of employee here is the value you may need,name: George employee_id:14296blood_group:b positive this is the blood group of the employeeage:32"
arr = ['name','employee_id','blood_group','age']

for w in arr:
    str = str.replace(w, f'@@{w}')
print(str)

您可以簡單地循環 arr 並使用 str.replace function:

for repl in arr:
    strng.replace(repl, '@@'+repl)
    
print(strng)

但是,我強烈建議您更改變量名str ,因為它是保留關鍵字。

您可以替換該值並在替換值之前添加空格和雙倍@@,並在結果中將雙倍空格替換為一個空格。

str ="This is a sample text document which consists of all demographic information of employee here is the value you may need,name: George employee_id:14296blood_group:b positive this is the blood group of the employeeage:32"
arr=['name','employee_id','blood_group','age']

for i in arr:
    str = str.replace(i, " @@{}".format(i))
print(str.replace("  ", " "))

Output

This is a sample text document which consists of all demographic information of employee here is the value you may need, @@name: George  @@employee_id:14296 @@blood_group:b positive this is the blood group of the employee @@age:32

您可以按照以下方式將re模塊用於該任務

import re
txt = "This is a sample text document which consists of all demographic information of employee here is the value you may need,name: George employee_id:14296blood_group:b positive this is the blood group of the employeeage:32"
arr=['name','employee_id','blood_group','age']
newtxt = re.sub('('+'|'.join(arr)+')',r'@@\1',txt)
print(newtxt)

Output:

This is a sample text document which consists of all demographic information of employee here is the value you may need,@@name: George @@employee_id:14296@@blood_group:b positive this is the blood group of the employee@@age:32

說明:這里我使用正則表達式從您的列表中捕獲單詞並將每個單詞替換為@@word。 這是單遍,而不是使用多個 str.replace 時的 X 遍(其中 X 是arr的長度),因此對於arr很長的情況應該更有效。

作為替代方案,您可以在循環中將以下內容轉換為更長的列表。 @@ 之前似乎也有空格。

str= str[:str.find(arr[0])] + ' @@' + str[str.find(arr[0]):]

str= str[:str.find(arr[1])] + ' @@' + str[str.find(arr[1]):]

str= str[:str.find(arr[2])] + ' @@' + str[str.find(arr[2]):]

str= str[:str.find(arr[3])] + ' @@' + str[str.find(arr[3]):]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM