Python 如何检查在线文本文件中的字符串

How to check for string in online text file in Python

如何检查在线文本文件中的字符串?现在,我正在使用 urllib.request 读取数据,但我如何检查在线文本文件中的字符串?

from urllib.request import urlopen
import subprocess

textpage = urlopen(https://myhost.com/random.txt)
url_test_output = str(textpage.read(), 'utf-8')

#Open the file
fobj = open(url_test_output)
text = fobj.read().strip().split()
 
#Conditions
while True:
    check_input = str(input("What do you want to search? ")
    if check_input == "": #if no value is entered for the string
        continue
    if check_input in text: #string in present in the text file
        print("Matched")
        break
    else: #string is absent in the text file
        print("No such string found,try again")
        continue
fobj.close()

我认为 urllib 完全符合您的用例。

我不明白你为什么在文本已经在你的变量中可用时打开文件,这是你的代码的更正版本,根据你的要求使用在线 txt 文件,可在 www.w3.org 网站上找到(您可以根据自己的喜好更改 URL):

from urllib.request import urlopen

textpage = urlopen("https://www.w3.org/TR/PNG/iso_8859-1.txt")
text = str(textpage.read(), 'utf-8')

# Conditions
while True:
    check_input = str(input("What do you want to search? "))
    if check_input == "":  # if no value is entered for the string
        continue
    if check_input in text:  # string in present in the text file
        print("Matched")
        break
    else:  # string is absent in the text file
        print("No such string found, try again")
        continue

输出

What do you want to search? something
No such string found, try again
What do you want to search? SPACE
Matched

您也可以使用请求库,这是另一个例子:

#!/usr/bin/env python3

import requests as req

resp = req.get("https://www.w3.org/TR/PNG/iso_8859-1.txt")
text = resp.text

# Conditions
while True:
    check_input = str(input("What do you want to search? "))
    if check_input == "":  # if no value is entered for the string
        continue
    if check_input in text:  # string in present in the text file
        print("Matched")
        break
    else:  # string is absent in the text file
        print("No such string found, try again")
        continue

输出

What do you want to search? something
No such string found, try again
What do you want to search? SPACE
Matched