【问题标题】:Trying to find words in a separate text file尝试在单独的文本文件中查找单词
【发布时间】:2021-12-13 19:35:34
【问题描述】:

我目前正在尝试找出如何在单独的文本文件中查找单词。


我正在使用Python 3.x,我正在尝试创建一个服务器和客户端线程,并且客户端应该输入一个单词。
然后,服务器应该在给我的列表中找到 txt 文件中的单词。


我将如何搜索文件中的单词?
我应该使用标题导入它还是应该使用其他方法?

【问题讨论】:

  • 您可以打开文件(使用open)并将其存储在字符串中或运行 grep 命令。您是否只是想查看该单词是否在文本文件中?或者你有几个文件
  • 我写了一个可能对你有帮助的答案。检查一下。

标签: python python-3.x multithreading file sockets


【解决方案1】:

你可以试试这样的:

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")

说明


open 内置函数是这样使用的:

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

默认模式是'r',表示你要读取文件。


您可以通过多种方式处理文件,其中最常用的两种方式是:

  1. with 关键字
  2. 文件对象到变量的简单赋值

第一个例子:

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

第二个例子:

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

更多信息


如果您想了解有关使用 python 打开文件的更多信息,请查看:

【讨论】:

    猜你喜欢
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 2012-10-31
    • 1970-01-01
    • 2013-02-02
    • 2013-04-28
    • 1970-01-01
    相关资源
    最近更新 更多