gpt4 book ai didi

python - 在 Python 中将文件名拆分为单词和数字

转载 作者:太空宇宙 更新时间:2023-11-04 11:04:17 26 4
gpt4 key购买 nike

以下代码将字符串拆分为单词列表但不包括数字:

    txt="there_once was,a-monkey.called phillip?09.txt"
sep=re.compile(r"[\s\.,-_\?]+")
sep.split(txt)

['there', 'once', 'was', 'a', 'monkey', 'called', 'phillip', 'txt']

此代码为我提供了单词和数字,但仍包含“_”作为有效字符:

re.findall(r"\w+|\d+",txt)
['there_once', 'was', 'a', 'monkey', 'called', 'phillip', '09', 'txt']

我需要在任何一段代码中更改什么以最终得到所需的结果:

['there', 'once', 'was', 'a', 'monkey', 'called', 'phillip', '09', 'txt']

最佳答案

这里有一个快速的方法可以做到这一点:

re.findall(r"[a-zA-Z0-9]+",txt)

还有一个:

re.split(r"[\s\.,\-_\?]+",txt)

(你只需要转义连字符,因为它在字符类中有特殊含义)

关于python - 在 Python 中将文件名拆分为单词和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2762292/

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