【发布时间】:2019-10-22 21:10:01
【问题描述】:
我无法从 txt 文件中提取部分文本。使用 python 3,我在整个文本文件中具有以下格式:
integer stringOfFilePathandName.cpp string integer
...not needed text...
...not needed text...
singleInteger( zero or one)
---------------------------------
integer stringOfFilePathandName2.cpp string integer
...not needed text...
...not needed text...
singleInteger( zero or one)
---------------------------------
每个模式出现的不需要的文本行数不稳定。 如果可能的话,我需要将 stringOfFilePathandName.cpp 和 singleInteger 值保存到字典中,例如 {stringOfFilePathandName:(0 或 1)}。
文本包含我不需要的其他文件扩展名(如 .cpp)。另外,我不知道文件的编码,所以我将其读取为二进制。
我的问题与以下链接中解决的问题有共同之处:
Python read through file until match, read until next pattern
https://sopython.com/canon/92/extract-text-from-a-file-between-two-markers/ - 我不太明白
python - Read file from and to specific lines of text- 这是我尝试复制的,但仅适用于一个实例。我需要在整个文件中迭代这个过程。
目前我已经尝试过这种方法,它只适用于一次:
fileRegex = re.compile(r".*\.cpp")
with open('txfile',"rb") as fin:
filename = None
for line in input_data:
if re.search(fileRegex,str(line)):
filename = ((re.search(fileRegex,str(line))).group()).lstrip("b'")
break
for line in input_data:
if (str(line).lstrip("b'").rstrip("\\n'"))=="0" or (str(line).lstrip("b'").rstrip("\\n'"))=="1":
dictOfFiles[filename] = (str(line).lstrip("b'").rstrip("\\n'"))
del filename
我的想法是需要一个类似的迭代文件的过程。到目前为止,我遵循的方法是逐行的。可能,最好将整个文本保存到一个变量然后提取。欢迎任何想法,这已经困扰了我很长一段时间......
每个请求这里是文本文件:https://raw.githubusercontent.com/CGCL-codes/VulDeePecker/master/CWE-119/CGD/cwe119_cgd.txt
【问题讨论】:
-
请提供一些真实的字符串
-
您对
{b'stringOfFilePathandName.cpp': b'0', b'stringOfFilePathandName2.cpp': b'1'}输出是否满意?或者您想在结果中包含 UTF8 字符串,例如{'stringOfFilePathandName.cpp': '0', 'stringOfFilePathandName2.cpp': '1'}? -
@WiktorStribiżew 是的,没关系,我可以稍后再删除,谢谢
-
@Nikos 你不能去掉
b前缀,你需要重新编码这些值。请参阅下面的答案。 -
@Jan 我添加了一个链接