pythonfind检测字符串中的路径文件

2024-06-07 19:23:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让代码把文本中的所有路径都写给我。例如:

text = "hello. this is path: C:\Users\zivsi\noz\wave.txt"
print(path in the text)
(C:\Users\zivsi\noz\wave.txt)

我该怎么做? 多谢各位


Tags: path代码textin文本路径txthello
2条回答

尝试使用正则表达式来匹配字符串中的特定模式,请参阅re-library文档(正则表达式库)的here

我认为您可能会尝试在您的路径中找到一些文件系统。假设要查找的所有路径都包含文件系统。我将尝试这样做:

file_systems = ["c:","d:","f:"] # Your possible file systems here
file_extensions = [".txt",".csv", ".xml"] # Your file extensions here

# my text
text = r"hello. this is path: C:\Users\zivsi\noz\wave.txt"

# The position where the path starts/ends
idx_fs = 0
idx_fe = 0 

for i in range(len(text)):
    test_fs = text[i:i+2].lower()
    test_fe = text[i:i+4].lower()
    # Find the position where your file system starts
    if test_fs in file_systems:
        idx_fs = i
    if test_fe in file_extensions:
        idx_fe = i + 3
        break

path = text[idx_fs:idx_fe]
print(path) # This gives as result: C:\Users\zivsi\noz\wave.txt

我知道这有一个有限的用例,但它与您提供的路径一起工作,请让我知道这是否是您正在寻找的!:D

相关问题 更多 >

    热门问题