如何解决在文本文件中使用正则表达式在特定字符串之前查找单词
我对正则表达式世界非常陌生。我所拥有的是一个文本文件,我想在其中的特定字符串(在这种情况下为“ 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
解决方法
假设文件名为FailedPreconditionError: Error while reading resource variable rnn/multi_rnn_cell/cell_1/lstm_cell/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/rnn/multi_rnn_cell/cell_1/lstm_cell/kernel)
[[{{node rnn/multi_rnn_cell/cell_1/lstm_cell/kernel/Read/ReadVariableOp}}]]
During handling of the above exception,another exception occurred:
FailedPreconditionError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _do_call(self,fn,*args)
1382 '\nsession_config.graph_options.rewrite_options.'
1383 'disable_meta_optimizer = True')
-> 1384 raise type(e)(node_def,op,message)
1385
1386 def _extend_graph(self):
FailedPreconditionError: Error while reading resource variable rnn/multi_rnn_cell/cell_1/lstm_cell/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/rnn/multi_rnn_cell/cell_1/lstm_cell/kernel)
[[node rnn/multi_rnn_cell/cell_1/lstm_cell/kernel/Read/ReadVariableOp (defined at <ipython-input-11-60d6e5975cd9>:18) ]]
,则可以提取所有行,并使用正则表达式获取所需的所有数据。
file.txt
结果:
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']
的列表中,来打印所需的所有结果。然后,您可以使用它来获取变量中的值。
我相信这种解决方案更容易理解,因为它只是循环浏览并找到结果。
,您可以使用捕获组找到所需的单词。根据构成单词(表情符号?)的不同,它可能会略有不同。以下是一个广泛的定义-没有空格的任何内容。在此示例中,我仅将搜索结果存储在每一行上。无表示不匹配。否则,它是一个搜索对象,其中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():]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。