简体   繁体   English

Python 3.6从文本文件中删除了不以元音开头的单词

[英]Python 3.6 remove words that do not start with a vowel from a text file

I am learning Python 3.6. 我正在学习Python 3.6。 I would like to know how to remove a word that does not start with a vowel reading in from a text file. 我想知道如何从文本文件中删除不以元音读入开头的单词。 I have already a text file called someStates.txt so I don't have to read in from a path for now. 我已经有一个名为someStates.txt的文本文件,因此现在不必从路径读入。

When I run the code I get someState.txt not defined . 当我运行代码时,我得到someState.txt not defined I want the output to create a text file with words that don't start with a vowel. 我希望输出创建一个不以元音开头的单词的文本文件。

What am I doing wrong? 我究竟做错了什么?

infile = open('someStates.txt', 'r')
infile.close()

vowels = ('a', 'e', 'i', 'o', 'u','y','A','E','I','O','u','Y') 

filteredStates.txt = [state
                    for state in someStates.txt
                      if state[0].rstrip().lower()
                        not in vowels] 
infile = open('filteredStates.txt','w')
infile.close()
print( 'infile')

''' Im new to this, listening to many of the advice here this is what I got '''我对此很陌生,在这里听了很多建议,这就是我得到的

''' “””

#input

infile = open('someStates.txt', 'r') # read in a text file frome my directory

#process

filterState=[line.rstrip() for line in infile] 
infile.close() 

vowels = ('a', 'e', 'i', 'o', 'u','y','A','E','I','O','U','Y')

filterState=[state for state in filterState
                      if state[0].rstrip().lower()
                      not in vowels]
infile.close()


#output


print(filterState)
infile = open('someStates.txt', 'r')
infile.close()


                    for state in someStates.txt

That is not how it works ;) 那不是它的工作原理;)

open() returns a file object: https://docs.python.org/3/library/functions.html#open open()返回文件对象: https : //docs.python.org/3/library/functions.html#open

From the file object, you can then read data into a string variable with data = infile.read() . 然后,您可以从文件对象中将数据入一个字符串变量,该字符串变量为data = infile.read() (Do this before closing the file.) (在关闭文件之前执行此操作。)

Then you need to split the string into words with words = data.split() . 然后,您需要将字符串拆分为words = data.split() Only after that you can loop over the words. 只有在那之后,您才能遍历单词。

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

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