我目前正在尝试解决一个解决方案,其中我有一个值和一个文本文件 (.txt),我想在其中检查代码中的值是否在文本文件中的某处。
我目前所做的是我有一个如下所示的文本文件:
999486
1117978
990583
1128062
1120618
和一个看起来像这样的代码:
def filter():
item_name = '1128062'
keyword = [line.rstrip('\n') for line in open('keywords.txt')]
has_good = False
sentences = [item_name]
def check_all(sentence, ws):
return all(re.search(r'\b{}\b'.format(w), sentence) for w in ws)
for sentence in sentences:
if any(check_all(sentence, word) for word in keyword):
has_good = True
break
if not has_good or keyword == "":
print("Removed the keyword - " + str(item_name))
sys.exit()
脚本的作用是:
它有一个有值的 item_name。 打开关键字存储所有关键字
使用 check_all 函数和 for sentence in sentences: 我的想法是检查关键字是否在 txt 文件中匹配。如果是,那么我们就继续执行程序,如果不是,那么我们打印出 Removed the keyword 并 sys.exit 程序。
然而,当我现在尝试运行这个程序时,我收到一条错误消息
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Users\PC\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "C:/Users/test.py.py", line 324, in filter
if any(check_all(sentence, word) for word in keyword):
File "C:/Users/test.py.py", line 324, in <genexpr>
if any(check_all(sentence, word) for word in keyword):
File "C:/Users/test.py.py", line 321, in check_all
return all(re.search(r'\b{}\b'.format(w), sentence) for w in ws)
File "C:/Users/test.py.py", line 321, in <genexpr>
return all(re.search(r'\b{}\b'.format(w), sentence) for w in ws)
File "C:\Users\PC\AppData\Local\Programs\Python\Python36\lib\re.py", line 182, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or bytes-like object
我意识到这一定是关于
的问题def check_all(sentence, ws):
return all(re.search(r'\b{}\b'.format(w), sentence) for w in ws)
这就是我遇到的问题,我问你们如何检查 .txt 文件中的关键字是否匹配,如果不匹配,我们打印出 Removed the keyword 和 sys.exit 程序,如果匹配则我们什么都不做。
最佳答案
假设您只想打印 true
如果 keyword
在文件中,如果 keyword
则打印 False
不在文件中..尝试执行下面的代码...
文本文件::
999486
1117978
990583
1128062
1120618
程序::
def match_string(text):
result = False
keyword = [line.rstrip('\n') for line in open('keyword.txt')]
if text in keyword:
result = True
return result
match_string('999487')
返回 True
注意:我仍然无法理解您是需要匹配整个字符串还是匹配字符串的每个字符...
关于python - 如何检查一个值是否匹配一个txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54091928/