gpt4 book ai didi

python - 检测并提取字符串列表中不断变化的数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:30:38 26 4
gpt4 key购买 nike

假设我有一个音频文件名列表(它可以是任何包含连续数字的字符串列表),它们具有不同的命名方案,但所有文件名都包含轨道编号。

我想提取变化的数字。

示例 1

Fooband 41 - Live - 1. Foo Title
...
Fooband 41 - Live - 11. Another Foo Title

想要的结果

数字列表:1,2,3,...,11

示例 2

02. Barband - Foo Title with a 4 in it
05. Barband - Another Foo Title
03. Barband - Bar Title
...
17. Barband - Yet another Foo Title

想要的结果

数字列表:2,5,3,...,17

由于索引号的位置不固定,我(认为)我不能在那里使用正则表达式。

我有什么

  1. 找到字符串的公共(public)前缀和后缀并将其砍掉
  2. 看字符串左边/右边有没有数字
  3. 使用该数字获取索引

但是有一个问题:如果我为示例 1 找到一个公共(public)前缀,那么公共(public)前缀将是Fooband 41 - Live - 1,因此 1 会丢失(同样对于 Song X - 10、Song X - 11 等命名方案,...)

问题

检测和提取字符串列表中不断变化的数字(在相似位置)的好方法是什么?

我正在使用 Python(对于这个问题来说它并不重要)

如果我也能检测到罗马数字,那就更好了,但我怀疑那会困难得多。

最佳答案

f = open('data.txt')
data = []

pattern = "\d+|[IVX]+"
regex = re.compile(pattern)

for line in f:
matches = re.findall(regex, line)
data.append(matches)

f.close()

print data
transposed_data = zip(*data)
print transposed_data

for atuple in transposed_data:
val = atuple[0]

if all([num==val for num in atuple]):
next
else:
print atuple
break

数据.txt:

Fooband 41 - Live - 1. Foo Title
Fooband 41 - Live - 2. Foo Title
Fooband 41 - Live - 3. Foo Title
Fooband 41 - Live - 11. Another Foo Title

--输出:--

[['41', '1'], ['41', '2'], ['41', '3'], ['41', '11']]
[('41', '41', '41', '41'), ('1', '2', '3', '11')]
('1', '2', '3', '11')

数据.txt:

01. Barband - Foo Title with a 4 in it
05. Barband - Another Foo Title
03. Barband - Bar Title
17. Barband - Yet another Foo Title

--输出:--

[['01', '4'], ['05'], ['03'], ['17']]
[('01', '05', '03', '17')]
('01', '05', '03', '17')

数据.txt:

01 Barband - Foo Title with a (I) in it
01 Barband - Another Foo (II) Title
01. Barband - Bar Title (IV)
01. Barband - Yet another (XII) Foo Title

--输出:--

[['01', 'I'], ['01', 'II'], ['01', 'IV'], ['01', 'XII']]
[('01', '01', '01', '01'), ('I', 'II', 'IV', 'XII')]
('I', 'II', 'IV', 'XII')

关于python - 检测并提取字符串列表中不断变化的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16960070/

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