Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中检查联机文本文件中的字符串_Python_Python 3.6_Urllib - Fatal编程技术网

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

如何在Python中检查联机文本文件中的字符串,python,python-3.6,urllib,Python,Python 3.6,Urllib,如何从联机文本文件中检查字符串?现在,我正在使用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_

如何从联机文本文件中检查字符串?现在,我正在使用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文件,可在网站上找到(你可以用任何你喜欢的方式更改URL):

输出

What do you want to search? something
No such string found, try again
What do you want to search? SPACE
Matched
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
What do you want to search? something
No such string found, try again
What do you want to search? SPACE
Matched

目前在您的代码中有什么不起作用?我不确定我是否理解这个问题。代码出了什么问题?如果您不想读取文件(为了进行搜索),并且希望在“服务器端”执行此操作,那么您必须拥有一个带有代码的web服务器,该代码将通过用户输入获得API调用。此API将返回匹配项。