使用python 3.0编程的新手。
我必须编写一个程序,它接受.txt文件的输入文件名,读取文件但只读取某些单词,忽略浮点数和整数以及任何与其他列表中的任何内容都不匹配的单词。
基本上,我有wordsList和messages.txt。 该程序必须通读messages.txt(文本示例:
)[41.298669629999999,-81.915329330000006] 6 2011-08-28 19:02:36工作需要飞过......我很高兴看到间谍小孩4带着对我生命的热爱...... ARREIC)< / p>
然后必须忽略所有数字并搜索消息中的任何单词是否与wordsList中的单词匹配,然后将这些单词与hvList中的值(int)匹配。
到目前为止我所拥有的:(单词List和hvList位于代码的另一部分,我认为没有必要显示我正在尝试做什么(让我知道你是否需要帮助它) )
def tweetsvalues ():
tweetwList = []
tinputfile = open(tweetsinputfile,"r")
for line in tinputfile:
entries = line.split()
最后一行entries = line.split()
是我猜中需要改变的那一行。
答案 0 :(得分:0)
是的,拆分是您最好的朋友。您还可以查找is方法的文档。虽然完整代码超出了StackOverflow的正常范围,但您的中心工作看起来像
words = sentence.split()
good_words = [word for word in words if isalpha(word)]
这可以使用过滤器以“Pythonic”方式完成,删除标点符号等。但是,从你在帖子中写的方式来看,我怀疑你可以从这里开始。
答案 1 :(得分:0)
这是我今天早些时候作为一个非常基本的拼写检查器编写的一些代码。我会更具体地回答你的问题,但我现在还没有时间。这应该可以实现您的目标。我打开的硬编码.txt文件包含很多拼写正确的英文单词。您可以根据需要随意补充我的想法,但请务必了解您正在使用的所有代码,否则我只会通过向您提供此代码来阻碍您的学习。在你的情况下,你可能想要输出所有的单词而不管它们的拼写,在我的代码中,我只输出拼写错误的单词。随意提出任何问题
#---------------------------------------------------------
# The "spellCheck" function determines whether the input
# from the inputFile is a correctly spelled word, and if not
# it will return the word and later be written to a file
# containing misspelled words
#---------------------------------------------------------
def spell_check(word, english):
if word in english:
return None
else:
return word
#---------------------------------------------------------
# The main function will include all of the code that will
# perform actions that are not contained within our other
# functions, and will generally call on those other functions
# to perform required tasks
#---------------------------------------------------------
def main():
# Grabbing user input
inputFile = input('Enter the name of the file to input from: ')
outputFile = input('Enter the name of the file to output to: ')
english = {} # Will contain all available correctly spelled words.
wrong = [] # Will contain all incorrectly spelled words.
num = 0 # Used for line counter.
# Opening, Closing, and adding words to spell check dictionary
with open('wordlist.txt', 'r') as c:
for line in c:
(key) = line.strip()
english[key] = ''
# Opening, Closing, Checking words, and adding wrong ones to wrong list
with open(inputFile, 'r') as i:
for line in i:
line = line.strip()
fun = spell_check(line, english)
if fun is not None:
wrong.append(fun)
# Opening, Closing, and Writing to output file
with open(outputFile, 'w') as o:
for i in wrong:
o.write('%d %s\n' % (num, i))
num += 1
main()