如何在python中处理文本文件

2024-10-02 00:39:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何用python打开文本文件。但我不知道如何处理这个文本文件以及如何使用python从文本文件中提取数据。我有一个名为words.txt的文件名,里面有字典里的单词。我调用这个文件并要求用户输入一个单词。然后尝试找出这个单词是否存在于这个文件中,如果是printTrue或者Word not found。你知道吗

wordByuser  = input("Type a Word:")
file = open('words.txt', 'r')

if wordByuser in file: #or if wordByuser==file:
    print("true")
else:
    print("No word found")

那个文字.txt文件在一行中包含每个字母,然后在第二行中包含新字母。一部分文字.txt如下所示:

AB
ab-
ABA
Ababa
Ababdeh
Ababua
abac
abaca
abacay
abacas
abacate
abacaxi
abaci
abacinate
abacination
abacisci
abaciscus
abacist
aback
abacli
Abaco
abacot
abacterial
abactinal
abactinally
abaction
abactor
abaculi
abaculus
abacus
abacuses

Tags: 文件数据txtif文件名字母单词word
3条回答

此函数应执行以下操作:

def searchWord(wordtofind):
    with open('words.txt', 'r') as words:
        for word in words:
            if wordtofind == word.strip():
                return True
    return False

使用此单线解决方案:

lines = file.read().splitlines()
if wordByuser in lines:
    ....

首先阅读file,同时使用snake_casehttps://www.python.org/dev/peps/pep-0008/

user_word  = input("Type a Word:")
with open('words.txt') as f:
    content = f.read()
    if user_word in content:
        print(True)
    else:
        print('Word not found')

相关问题 更多 >

    热门问题