Python读取文件//创建新列表

Python读取文件//创建新列表,python,Python,基本上,我有一个包含单词列表的文本文件。然后我必须创建一个原始输入,让用户输入单词,如果输入的单词在文本文件中,它将打印“Right”。对于任何不在列表中的单词,我必须把它放在一个不同的文件中,其中包含“错误”单词的数量 在大多数情况下,我的用户输入是正确的,如果输入的单词在文本文件中,它将响应是否正确。。但是我很难将错误的单词添加到另一个文件中 print 'Opening file wordlist.txt' b = open('wordlist.txt') print 'Reading

基本上,我有一个包含单词列表的文本文件。然后我必须创建一个原始输入,让用户输入单词,如果输入的单词在文本文件中,它将打印“Right”。对于任何不在列表中的单词,我必须把它放在一个不同的文件中,其中包含“错误”单词的数量

在大多数情况下,我的用户输入是正确的,如果输入的单词在文本文件中,它将响应是否正确。。但是我很难将错误的单词添加到另一个文件中

print 'Opening file wordlist.txt'
b = open('wordlist.txt')

print 'Reading file wordlist.txt'
word_list = b.readlines().lower().split()
b.close()

in_word = raw_input('Enter a word: ')
if in_word+'\n' in word_list:
print 'Right'



wrong_list = { word for word in in_word if word not in word_list}
return wrong_list
为什么不呢

wrong_list = []

print 'Opening file wordlist.txt'
b = open('wordlist.txt')

print 'Reading file wordlist.txt'
word_list = b.readlines().lower().split()
b.close()

in_word = raw_input('Enter a word: ')
if in_word+'\n' in word_list:
    print 'Right'

else:
    wrong_list.extend(in_word)
为什么不呢

wrong_list = []

print 'Opening file wordlist.txt'
b = open('wordlist.txt')

print 'Reading file wordlist.txt'
word_list = b.readlines().lower().split()
b.close()

in_word = raw_input('Enter a word: ')
if in_word+'\n' in word_list:
    print 'Right'

else:
    wrong_list.extend(in_word)
试试这个:

in_word = ''
wrong_list = []

with open('wordlist.txt', 'r') as f:
    word_list = f.read().lower().split()

while in_word is not '#':
    in_word = raw_input('Enter a word(type # to exit): ')

    if in_word is '#':
        break

    if in_word in word_list:
        print 'right'
    else:
        print 'wrong'
        wrong_list.append(in_word)

result = """Number of wrong words: %d
Wrong words: %s
""" % (len(wrong_list), ','.join(wrong_list))

print result

with open('wrong.txt', 'a') as f:
    f.write(result)
试试这个:

in_word = ''
wrong_list = []

with open('wordlist.txt', 'r') as f:
    word_list = f.read().lower().split()

while in_word is not '#':
    in_word = raw_input('Enter a word(type # to exit): ')

    if in_word is '#':
        break

    if in_word in word_list:
        print 'right'
    else:
        print 'wrong'
        wrong_list.append(in_word)

result = """Number of wrong words: %d
Wrong words: %s
""" % (len(wrong_list), ','.join(wrong_list))

print result

with open('wrong.txt', 'a') as f:
    f.write(result)

当前实现中的问题是您需要知道如何缩进以及如何使用python的if语句的一些特性,即“else”

关于这个非常相关的话题,这里有一个很棒的教程。

您还需要知道如何打开文件进行写入。 解释如下: 这很简单:

with open('/path/filename_here.txt','w') as writeable_file:
    #do stuff here with the file
    writeable_file.write(line_to_write)
#the file is closed now.

当前实现中的问题是您需要知道如何缩进以及如何使用python的if语句的一些特性,即“else”

关于这个非常相关的话题,这里有一个很棒的教程。

您还需要知道如何打开文件进行写入。 解释如下: 这很简单:

with open('/path/filename_here.txt','w') as writeable_file:
    #do stuff here with the file
    writeable_file.write(line_to_write)
#the file is closed now.