假设我在列表中有以下字符串集合:
list_of_strings = [ "data_1 = 3,", "re = 3,", "item = 5"]
现在我想找到字符串“ item”,并将以下数字5替换为f。 10整行:
item = 10
使用 regex 可以找到“ item”,但我不知道如何指向该数字并进行更改。
说明:
最终目标是拥有一个在字符串列表中搜索给定字符串并交换与该字符串关联的值的函数:
match_str = item_x
change_value = 10
list = ["string1","string2","string5","item_x = 3", ...]
change_parameter(match_str,change_value,list)
最好change_value可以是字符串或浮点数
答案 0 :(得分:3)
您不仅需要找到单词class Location
{
constructor(name = "Dummy Location", lat = 0.0, lng = 0.0)
{
this.name = name;
this.lat = lat;
this.lng = lng;
}
}
function geocode(location)
{
axios.get('https://maps.googleapis.com/maps/api/geocode/json?',
{
params: {
address: location,
key: googleAPIKey
}
})
// Get a reponse from that request
.then(function(response)
{
///Format the address
var formattedAddress = response.data.results[0].formatted_address;
// Get the various address components
var locationName = `${response.data.results[0].address_components[0].long_name}, ${response.data.results[0].address_components[2].short_name}`;
var locationLat = response.data.results[0].geometry.location.lat;
var locationLng = response.data.results[0].geometry.location.lng;
// Create a new Location based on those components
var geoLocation = new Location(locationName, locationLat, locationLng);
// (Debug) Log that location
console.log(geoLocation);
// Return that location
return geoLocation;
})
.catch(function(error)
{
console.log(error);
})
}
,还可以在正则表达式中包含以下数字,然后将整个内容替换为<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cool Weather App</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel = "stylesheet" href="css/styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<header>
<div id = "locationinputcontainer">
<input id="locationfield" type="text" value="Location">
<input id = "submitbutton" type="submit" value="Submit">
<input id = "savelocationbutton" type = "submit" value = "Save Location">
</div>
</header>
<div id = "locationweathercontainer">
<h1 id = "locationname">Dummy Value</h1>
<h2 id = "weather">Weather</h2>
<h1 id = "temperature">68°F</h1>
<h3 id = "precipitation">Precipitation:</h3>
<h3 id = "humidity">Humidity: </h3>
<h3 id = "windspeed">Wind Speed: </h3>
</div>
<div id = "mylocationscontainer" class = "dropdowncontainer" style = "float:left">
<h1>My Locations</h1>
<ol>
</ol>
</div>
<div id = "settingscontainer" class = "dropdowncontainer" style = "float:right">
<h1>Settings</h1>
</div>
</body>
<script src = "js/location.js"></script>
<script>
const locationField = document.querySelector("#locationfield");
const submitButton = document.querySelector("#submitbutton");
const saveButton = document.querySelector("#savelocationbutton");
const locationNameElement = document.querySelector("#locationname");
const locationsListElement = document.querySelector("#mylocationscontainer");
const prefix = "asb9599-";
const storedLocationsKey = prefix + "storedLocations";
const storedCurrentLocationKey = prefix + "storedCurrentLocation";
let currentLocation;
let locationInput;
/* Functions */
function UpdateCurrentLocation()
{
currentLocation = geocode(locationInput);
console.log("(index.html) Current Location: " + currentLocation);
locationNameElement.innerHTML = currentLocation.name;
}
/* Events */
submitButton.onclick = UpdateCurrentLocation;
locationField.onchange = e => {locationInput = e.target.value};
</script>
</html>
。
item
匹配一个或多个空格字符,如果您希望空格是可选的,则可以使用item = 10
,它匹配零个或多个空格字符。
\s+
编辑:
要遵守您的最新更改,即使其通用。让我们编写一个函数,该函数搜索一些值并替换它的值。我将使用与目前相同的方法。
\s*
现在,让我们针对不同的值测试此>>> l = ['data_1 = 3', 're = 3', 'item = 5']
>>> import re
>>> r = re.compile(r'item\s*=\s*\d+')
>>> updated_l = [r.sub('item = 10', s) if r.match(s) else s for s in l]
>>> print(updated_l)
['data_1 = 3', 're = 3', 'item = 10']
方法:
def change_parameter(match_str, change_value, list1):
# First, let's create a regex for it, and compile it
r = re.compile(r'{0}\s*=\s*\d+'.format(match_str))
# Find, and replace the matching string's value
updated_l = [r.sub('{0} = {1}'.format(match_str, change_value), s) if r.match(s) else s for s in list1]
return updated_l
对于字符串和浮点替换:
change_parameter
答案 1 :(得分:1)
一种更好,更通用的解决方案是使用记录在案的re.sub
功能来接受替换函数(给Match对象,您可以将字符串返回以替换)。您可以这样编写它,使其适用于任何key = val
字符串。当然,有很多方法可以做到这一点,但是您提到了正则表达式,所以这是一种方法。
from functools import partial
import re
def subst_val(newval, m):
return '{} = {}'.format(m.group('key'), newval)
keyval_re = re.compile(r'(?P<key>[^= ]+)\s*=\s*(?P<val>.+)')
您可以在哪里根据需要的确切语法来调整正则表达式。然后像这样使用它:
keyval_re.sub(partial(subst_val, 10)), 'item = 5')
,它将返回“ item = 10”。无论LHS密钥是什么,它都将相同。老实说,有更简单的方法可以做到这一点,但是这一方法相当强大。
答案 2 :(得分:0)
假设您要就地修改列表 ,以便我可以从其他答案中无法探索的角度进行开发,我们可以继续使用列表元素的枚举,循环进行,以便所有以"item"
开头的列表元素,我们使用re.sub
来更改数字(并且不仅更改数字……而且不仅更改5
,而且更改每个数字序列...)>
for i, element in enumerate(data):
if element.startswith("item"):
data[i] = re.sub("[0-9]+", "10", element)
P.S。 如果元素以item
开头且不包含数字,则该元素将通过替换保持不变。
答案 3 :(得分:-1)
我不确定您所说的字符串集合是什么意思(在您的示例中定义了变量。但这也许可以解决您的情况)使用replace()
函数:
string.replace(s,old,new [,maxreplace])
返回字符串s的副本,其中包含所有出现的子字符串old 换成新的。如果给出了可选参数maxreplace,则 第一次出现最大置换事件。
string = """
data_1 = 3,
re = 3,
item = 5.
"""
new_str = string.replace("item = 5", "item = 10")
print(new_str)
输出:
data_1 = 3,
re = 3,
item = 10.