我是python编程的初学者,并且正在寻找一个函数来帮助我读取特定字符后的每一行文件,例如:
这是文本文件的格式。
<ABC>
language \sometext.com xyz
包含这些示例句子的文本文件,我只需要在“和”之间的字符串。(在上面的示例中只有“文本”。)
这是代码,但我无法100%输出。
f = open("test.txt", "r")
for x in f:
if "\\" in x:
x = x.rstrip('\\')
print(x)
在上面的代码中,我只是得到第一行的输出,例如:
language sometext.com xyz
您正在调用readline
两次,line
用文本文件的第二行覆盖变量。代码中的第二和第三行实际上什么也没做。
编辑:原来的问题已被编辑,问题现在稍有不同。我对使用正则表达式的建议仍然有效。
我将使用regex和python的内置re模块:
import re
regex = re.compile(r"\\(.+)\.") # Pattern matching anything beween \ and .
with open("test.txt", "r") as file:
results = regex.findall(file.read())
print(results)
# Returns a list of every sub-string bewtween \ and . in the text file.
如果要逐行执行此操作:
file = open("test.txt", "r")
line = file.readline()
result = regex.search(line).group(1) # ".group(1)" makes sure the \ and . are not included
print(result)
# then you can continue with the next line
line = file.readline()
result = regex.search(line).group(1)
print(result)
# etc
# You can do this in a loop
# or with file.readlines() which returns a list of all the lines in the file
如果您想了解有关python中的正则表达式(正则表达式)的更多信息,请查看此出色的介绍:https : //automatetheboringstuff.com/2e/chapter7/
或官方文档:https : //docs.python.org/3/library /re.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句