如何在python的同一行中提取2个字符之间的字符串

时间:2019-03-07 18:39:51

标签: python string file

任务

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

\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

感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

尝试一下:

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

答案 1 :(得分:0)

您可以使用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

答案 2 :(得分:0)

如果我是你,我会使用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