【问题标题】:python-find detect path file in stringpython-find 检测字符串中的路径文件
【发布时间】: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)

我该怎么做? 谢谢

【问题讨论】:

  • 你熟悉正则表达式吗?

标签: python string file path


【解决方案1】:

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

【讨论】:

  • 我能得到帮助吗?我不知道我应该使用什么
  • 您需要什么样的帮助?您是否点击了我的答案中的“此处”?
  • 是的,但我没有不喜欢你的问题
  • 我不知道如何使用正则表达式
  • 在正则表达式中,您有一个由符号组成的模式(例如点“。”表示任何字符)和一个文本(您的字符串),re 库允许您在字符串中搜索您的模式,并返回结果。在您的情况下,您可以尝试这种模式 "C:(\\(.)*)*txt" → 它搜索 "C:" 后跟 "\" 尽可能多地重复,然后是 "txt"
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多