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

问题描述

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

/**
 * Run some code in it's own thread
 * @params - Any parameters you want to be passed into the thread
 * @param - The last parameter must be a function that will run in it's own thread
 * @returns - An promise-like object with a `then`,`catch`,and `abort` method
 */
function Thread() {
  var worker;
  const promise = new Promise((resolve,reject) => {
    var args = Array.from(arguments);
    var func = args.pop();
    if (typeof func !== "function") throw new Error("Invalid function");
    var fstr = func.toString();
    var mainBody = fstr.substring(fstr.indexOf("{") + 1,fstr.lastIndexOf("}"));
    var paramNames = fstr.substring(fstr.indexOf("(") + 1,fstr.indexOf(")")).split(",").map(p => p.trim());
    var doneFunct = paramNames.pop();
    if (paramNames.length !== args.length) throw new Error("Invalid number of arguments.");
    var workerStr = `var ${doneFunct} = function(){
            var args = Array.from(arguments);
            postMessage(args);
        };
        self.onmessage = function(d){
            var [${paramNames.join(",")}] = d.data;
            ${mainBody}
        };`;
    var blob = new Blob([workerStr],{
      type: 'application/javascript'
    });
    worker = new Worker(URL.createObjectURL(blob));
    worker.onerror = reject;
    worker.onmessage = (d) => {
      resolve(...d.data);
      worker.terminate();
    };
    worker.postMessage(args);
  });
  return {
    then: (...params)=>promise.then(...params),catch: (...params)=>promise.catch(...params),abort: ()=>worker.terminate()
  }
}

////////////////////////
//// EXAMPLE USAGE /////
////////////////////////

// the thread will take 2 seconds to execute
// and then log the result
var myThread = new Thread("this is a message",2,function(message,delaySeconds,exit) {
  setTimeout(() => {
    exit(message.split('').reverse().join(''));
  },delaySeconds * 1000);
});

myThread.then(result => console.log(result));

// the thread will take 2 seconds to execute
// but we will cancel it after one second
var myThread = new Thread("this is a message",delaySeconds * 1000);
});

setTimeout(()=>{
  myThread.abort();
},1000);

解决方法

我认为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
What do you want to search? SPACE
Matched

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...