【问题标题】:How to extract the string between 2 characters in same line on python如何在python的同一行中提取2个字符之间的字符串
【发布时间】:2019-07-29 17:56:13
【问题描述】:

任务

我有一个带有字母数字文件名的文本文件:

\abc1.txt.  \abc2.txt     \abc3.txt     \abcde3.txt
\Zxcv1.txt        \mnbd2.txt     \dhtdv.txt

我需要从文件中提取所有.txt 扩展名,这些扩展名将在 python 文件中的同一行和不同行中。

期望的输出:

abc1.txt
abc2.txt
abc3.txt
abcde3.txt
Zxcv1.txt
mnbd2.txt
dhtdv.txt

感谢您的帮助。

【问题讨论】:

  • 到目前为止你有什么尝试?

标签: python string file


【解决方案1】:

如果我是你,我会使用regular expressions(正则表达式)。

import re

# Open the file with the mode r, which means read the file
with open("text_file.txt", "r") as f:
    # Actually read the content of the file
    file_content = f.read()

# Find everything which matches the given regex code
# This returns a list of the matches
files = re.findall(r"\\(.*?.txt)", file_content)

# Iterate through each item in the list
for file in files:
    # Print the item
    print(file)

这是我使用的正则表达式的解释:https://regex101.com/r/DAPlqM/1

【讨论】:

  • 对于更精确匹配的文件 = re.findall(r"\(.*?.txt\b)", file_content) 会有所帮助
  • @Justin 请记住,您必须转义反斜杠。所以这样更好:files = re.findall(r"\\(.*?.txt\b)", file_content)
【解决方案2】:

试试这个:

string = r"\abc1.txt. \abc2.txt \abc3.txt \abcde3.txt \Zxcv1.txt \mnbd2.txt \dhtdv.txt"
list = string.split("\\")
print(list)
formatted = "\n".join(list)
print(formatted)

结果:

['', 'abc1.txt. ', 'abc2.txt ', 'abc3.txt ', 'abcde3.txt ', 'Zxcv1.txt ', 'mnbd2.txt ', 'dhtdv.txt']

abc1.txt. 
abc2.txt 
abc3.txt 
abcde3.txt 
Zxcv1.txt 
mnbd2.txt 
dhtdv.txt

【讨论】:

    【解决方案3】:

    您可以将re.findall 与匹配由. 分隔的两个单词的模式一起使用:

    import re
    print('\n'.join(re.findall(r'\w+\.\w+', s)))
    

    给定变量s 中的输入文本,输出:

    bc1.txt
    bc2.txt
    bc3.txt
    bcde3.txt
    Zxcv1.txt
    mnbd2.txt
    dhtdv.txt
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-20
      • 1970-01-01
      • 2013-02-09
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      相关资源
      最近更新 更多