【发布时间】:2020-08-13 20:08:37
【问题描述】:
我希望代码将文本中的所有路径都写给我。例如:
text = "hello. this is path: C:\Users\zivsi\noz\wave.txt"
print(path in the text)
(C:\Users\zivsi\noz\wave.txt)
我该怎么做? 谢谢
【问题讨论】:
-
你熟悉正则表达式吗?
我希望代码将文本中的所有路径都写给我。例如:
text = "hello. this is path: C:\Users\zivsi\noz\wave.txt"
print(path in the text)
(C:\Users\zivsi\noz\wave.txt)
我该怎么做? 谢谢
【问题讨论】:
尝试使用正则表达式匹配字符串中的特定模式,请参阅here 获取 re 库文档(正则表达式库)。
【讨论】:
我认为您可能会尝试在您的路径中找到一些文件系统。假设您要查找的所有路径都包含文件系统。我会尝试这样做:
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
【讨论】: