【问题标题】:Comparing a string to a .txt file将字符串与 .txt 文件进行比较
【发布时间】:2022-01-06 22:09:29
【问题描述】:

我之前发布了一个关于在浏览器历史记录中读取字符串元素的问题,但现在我意识到我需要将该字符串文件的元素与外部 .txt 文件进行比较。这是我使用的。

from browser_history.browsers import Chrome

f = Chrome()

outputs = f.fetch_history()

string1 = str(outputs.histories)

file1 = open("grey.txt", "r")

readfile = file1.read()

if string1 in readfile:
    print("TRUE")
else:
    print("NAH FAM")

file1.close()

我在 .txt 文件中有 google 一词。我知道 google.com 在浏览器历史模块输出的字符串中。

if 'google' in str(outputs.histories):
    print(True)

那行代码打印正确,但是使用外部文本文件似乎不起作用。

【问题讨论】:

  • 文件末尾是否有尾随换行符?如果你在 file1.read() 之后添加“.strip()”会改变什么吗?
  • @inteoryx。我想进一步的问题是文本文件里面会有几个术语,如果字符串中只有一个术语与文本文件中的几个术语之一匹配,它将吐出一个真实的值。现在,除非只有一个值(该值为真),否则它将吐出 false。

标签: python string text browser-history


【解决方案1】:

我同意评论中的@inteoryx。

我认为问题出在空格上。 当您将外部文件加载为 string 时,会选择整行。

另外,我觉得这里面也有错误,`

if string1 in readfile :

应该这样做:

if readfile in string1:

你应该这样做:

from browser_history.browsers import Chrome

f = Chrome()

outputs = f.fetch_history()

string1 = str(outputs.histories)

file1 = open("grey.txt", "r")

readfile = file1.read()

readfile = str(readfile)
readfile = readfile.strip()

if readfile in string1:
    print("TRUE")
else:
    print("NAH FAM")

file1.close()

编辑: 对于多项检查,可以这样做:

from browser_history.browsers import Chrome

f = Chrome()

outputs = f.fetch_history()

string1 = str(outputs.histories)
count = 0

file1 = open("grey.txt", "r")

readfile = file1.read()

readfile = str(readfile)
readfile = readfile.strip()

read = readfile.split(',')

for i in read :
    
    if i in string1:
        count = count+1


if count == len(read) :
    print("True" , len(read))
else :
    print("NAH FAM")
file1.close()

`

【讨论】:

  • 这确实适用于单个元素,但我不妨只使用一个字符串。在文本文件中放置多个术语时,它总是会打印 no,即使其中一个术语存在于字符串中。另一个不存在导致否。我希望将一些术语放在文本文件中,如果只有其中一个存在,它会吐出一个真实的。希望这是有道理的!我不相信将任何内容放入代码中会有所帮助,因为我相信任何内容都必须具有可迭代性。
  • 文本文件中用来分隔单词的分隔符是什么?
  • 逗号,例如我会去 Youtube、Google、Twitter。即使我去了 google 和 twitter,但没有去 youtube,它也会被认为是错误的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-10
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多