我对这个世界很陌生。我所拥有的是一个文本文件,我希望在其中的特定字符串(在本例中是“out”)之前找到一个特定的单词,并将其存储到一个变量中。所以我可以在后面的代码中用其他的东西来替换它。下面,我将把<>围绕我正在寻找的有趣的单词,只是为了突出的目的。如果有人能给我指明正确的方向,那就太棒了。我拥有的文本文件如下:在本例中,我希望找到用< >突出显示的单词。如果我的问题不像描述我想要的东西那样清晰,我会提前道歉。
neighbor 10.242.1.1 route-map LOCAL_PREF in
neighbor 10.242.1.1 route-map <grn200_NWK> out
neighbor 10.244.206.2 route-map LOCAL_PREF in
neighbor 10.244.206.2 route-map <blu330_NWK> out
neighbor 10.242.120.202 route-map LOCAL_PREF in
neighbor 10.242.120.202 route-map <grn200_NWK> out
.
.
.
the text file continues in this pattern发布于 2020-08-18 00:55:16
假设您的文件名为file.txt,您可以获取所有行,并使用regex获取所需的所有数据。
import re
with open('file.txt') as f:
contents = f.readlines() # get the lines in a list
for x in contents: # iterate through each line
matched = re.search(r'\S+ out$', x) # find results
if matched:
result.append(matched.group().split(" ")[0]) # save results
print(result)结果:
['blu330_NWK', 'grn200_NWK']
这将通过获取文件中的所有行来打印所需的所有结果,然后循环遍历,找到文本并将名为results的列表保存在其中。然后,您可以使用它来获取变量中的值。
我相信,这个解决方案更容易理解,因为它只是循环的线条和发现的结果。
发布于 2020-08-18 00:52:18
您可以使用捕获组来查找您想要的单词。根据构成一个单词的成分(表情符号?),它可能略有不同。下面是一个扩展的定义-任何没有空格的东西。在这个例子中,我只是将搜索结果存储在每一行上。A没有意味着没有匹配。否则,它是一个搜索对象,其中group(1)是找到的单词,start()是它的开始索引,end()是它的结束索引。举个例子,我把这个词改成了"foo“。
import re
with open('foo.txt') as fileobj:
searches = [(re.search(r"(\S+) out$", line.strip()) for line in fileobj]
matched = []
for match, line in searches:
if match:
print("matched", match.group(1))
matched.append(line[:match.start()] + "foo" + line[match.end():]https://stackoverflow.com/questions/63460302
复制相似问题