如何在python中处理文本文件

时间:2018-10-16 07:09:32

标签: python data-extraction

我知道如何在python中打开文本文件。但是我不知道如何处理该文本文件以及如何使用python从文本文件中提取数据。我有一个名为words.txt的文件名,其中包含字典词。我称呼这个文件,要求用户输入一个单词。然后尝试找出天气,该单词是否存在于此文件中,如果是,则打印True,否则打印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")

words.txt文件在一行中包含每个字母,然后在第二行中包含新字母。以下是word.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

4 个答案:

答案 0 :(得分:2)

使用这一行解决方案:

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

答案 1 :(得分:0)

此功能应执行以下操作:

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

答案 2 :(得分:0)

您只需要在启动的文件类中添加.read()

赞:

wordByuser  = input("Type a Word:")
file = open('words.txt', 'r')
data = file.read()
if wordByuser in data:
    print("true")
else:
    print("No word found")

答案 3 :(得分:0)

首先阅读file,也使用snake_case https://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')