简体   繁体   English

尝试在单独的文本文件中查找单词

[英]Trying to find words in a separate text file

So I'm currently trying to figure out how to find a word in a separate text file.所以我目前正试图弄清楚如何在单独的文本文件中找到一个词。 I'm using Python3 and I'm trying to make a server and client thread and the client is supposed to input a word.我正在使用 Python3 并且我正在尝试创建一个服务器和客户端线程,并且客户端应该输入一个单词。 The server then is supposed to find the word in the list given to me that's in a txt file.然后服务器应该在给我的列表中找到一个 txt 文件中的单词。 How would I go about searching for the word in the file.我将如何搜索文件中的单词。 Do I import it with a header or is there a different approach I should use?我是使用标头导入它还是应该使用不同的方法?

You can try something like this:你可以尝试这样的事情:

with open(r"C:\Path\to\file.txt", 'r') as file:
    content = file.read()
if ("my word" in content):
    print("Your string is in the file")
else:
    print("String not found")

Explaination说明


The open built-in function is used like this: open内置函数是这样使用的:

file = open(r"C:\\Your\path\{file_name}.{file_extension}", mode_for_opening_the_file)

The default mode is 'r' , which means you are going to read the file.默认模式是'r' ,这意味着您要读取文件。


You can handle a file in more ways, the two most used of which are:您可以通过更多方式处理文件,其中最常用的两种方式是:

  1. The with keyword with关键字
  2. The simple assignation of the file object to a variable将文件对象简单地分配给变量

First example:第一个例子:

with open(r"MyFile.json", 'r') as file:
    print(file.read())

Second example:第二个例子:

file = open(r"MyFile.json", 'w+')
file.write("Hello World")
file.close() # The with method automatically close the file, saving all the changes

Some more information更多信息


If you want more information about opening files with python, check this:如果您想了解有关使用 python 打开文件的更多信息,请查看以下内容:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM