gpt4 book ai didi

python - 读取带有字符串的列表并将其转换为 int() 但保留特定格式

转载 作者:太空宇宙 更新时间:2023-11-04 09:39:10 25 4
gpt4 key购买 nike

我有一个充满字符串的文件,我将其读入列表。现在我想通过查找 .../002/... 找到特定的行(例如下面的第一行)并添加到这些 002 +5 给我/007/,以便找到我的下一个包含/007/的行。

文件看起来像这样

https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/002/MYD021KM.A2018002.1345.006.2018003152137.hdf
https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/004/MYD021KM.A2018004.1345.006.2018005220045.hdf

有了这个我可以识别例如第一行:

match = re.findall("/(\d{3})/", data_time_filtered[i])

现在的问题是:如何将字符串转换为整数但保持格式 00X?这个 Ansatz 是否正确?:

match_conv = ["{WHAT's in HERE?}".format(int(i)) for i in match]

根据以下建议的答案进行编辑:

显然没有办法直接读取字符串中的数字并保持原样?

使用 zfill 和其他建议的函数向数字添加 0 会使它变得更加复杂,因为/00x/应保持最多 3 位数字(因为它们代表一年中的几天)。所以我一直在寻找一种有效的方法来保持字符串中的数字不变,并使它们“可数学化”。

最佳答案

我们可以先定义一个函数,将一个整数与一个字符串相加并返回一个字符串,用零填充以保持相同的长度:

def add_to_string(s, n):
total = int(s)+n
return '{:0{}}'.format(total, len(s))

add_to_string('003', 2)
#'005'
add_to_string('00030', 12 )
#'00042

然后我们可以使用 re.sub具有替换功能。我们使用正则表达式 r"(?<=/)\d{3}(?=/)"匹配一组 3 位数字,前后为 / , 不包括他们在比赛中。

替换函数将匹配项作为参数,并返回一个字符串。您可以对其进行硬编码,如下所示:

import re

def add_5_and_replace(match):
return add_to_string(match.group(0), 5)

url = 'https://nasa.gov/archive/allData/6/MYD021KM/2018/002/MYD021KM.hdf'

new = re.sub(r"(?<=/)\d{3}(?=/)", add_5_and_replace, url)
print(new)
# https://nasa.gov/archive/allData/6/MYD021KM/2018/007/MYD021KM.hdf

但传递附加值可能会更好。要么使用 lambda:

def add_and_replace(match, n=1):
return add_to_string(match.group(0), n)

url = 'https://nasa.gov/archive/allData/6/MYD021KM/2018/002/MYD021KM.hdf'

new = re.sub(r"(?<=/)\d{3}(?=/)", lambda m: add_and_replace(m, n=5), url)

或者偏函数。一个完整的解决方案可能是:

import re
from functools import partial

def add_to_string(s, n):
total = int(s)+n
return '{:0{}}'.format(total, len(s))

def add_and_replace(match, n=1):
return add_to_string(match.group(0), n)

url = 'https://nasa.gov/archive/allData/6/MYD021KM/2018/002/MYD021KM.hdf'

new = re.sub(r"(?<=/)\d{3}(?=/)", partial(add_and_replace, n=3), url)
print(new)

# https://nasa.gov/archive/allData/6/MYD021KM/2018/005/MYD021KM.hdf

如果你只想给你的数字加上默认值1,你可以简单地写

new = re.sub(r"(?<=/)\d{3}(?=/)", add_and_replace, url)
print(new)

# https://nasa.gov/archive/allData/6/MYD021KM/2018/003/MYD021KM.hdf

关于python - 读取带有字符串的列表并将其转换为 int() 但保留特定格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52326825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com