Python-无法将txt文件中的行拆分为单词

Python-无法将txt文件中的行拆分为单词,python,list,file-io,split,Python,List,File Io,Split,我的目标是打开一个文件,将其拆分为唯一的单词,并显示该列表以及数字计数。我想我必须把文件分成几行,然后把这些行分成单词,然后把它们全部添加到一个列表中 问题是,如果我的程序在无限循环中运行,并且不显示任何结果,或者它只读取一行,然后停止。正在读取的文件是葛底斯堡地址 def uniquify( splitz, uniqueWords, lineNum ): for word in splitz: word = word.lower() if word not in

我的目标是打开一个文件,将其拆分为唯一的单词,并显示该列表以及数字计数。我想我必须把文件分成几行,然后把这些行分成单词,然后把它们全部添加到一个列表中

问题是,如果我的程序在无限循环中运行,并且不显示任何结果,或者它只读取一行,然后停止。正在读取的文件是葛底斯堡地址

def uniquify( splitz, uniqueWords, lineNum ):
for word in splitz:
    word = word.lower()        
    if word not in uniqueWords:
        uniqueWords.append( word )

def conjunctionFunction():

    uniqueWords = []

    with open(r'C:\Users\Alex\Desktop\Address.txt') as f :
        getty = [line.rstrip('\n') for line in f]
    lineNum = 0
    lines = getty[lineNum]
    getty.append("\n")
    while lineNum < 20 :
        splitz = lines.split()
        lineNum += 1

        uniquify( splitz, uniqueWords, lineNum )
    print( uniqueWords )


conjunctionFunction()

你发现了你的代码有什么问题,但无论如何,我会稍微改变一下。由于您需要跟踪唯一单词的数量及其计数,因此应使用字典执行此任务:

wordHash = {}

with open('C:\Users\Alex\Desktop\Address.txt', 'r') as f :
    for line in f:
       line = line.rstrip().lower()

       for word in line:
            if word not in wordHash:
                wordHash[word] = 1

            else: 
                wordHash[word] += 1

print wordHash

你发现了你的代码有什么问题,但无论如何,我会稍微改变一下。由于您需要跟踪唯一单词的数量及其计数,因此应使用字典执行此任务:

wordHash = {}

with open('C:\Users\Alex\Desktop\Address.txt', 'r') as f :
    for line in f:
       line = line.rstrip().lower()

       for word in line:
            if word not in wordHash:
                wordHash[word] = 1

            else: 
                wordHash[word] += 1

print wordHash
将文件拆分为单词的最简单方法:

将文件拆分为单词的最简单方法:

假设从文件中检索inp

inp = """Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense."""


data = inp.splitlines()

print data

_d = {}

for line in data:
    word_lst = line.split()
    for word in word_lst:
        if word in _d:
            _d[word] += 1
        else:
            _d[word] = 1

print _d.keys()
输出

['Beautiful', 'Flat', 'Simple', 'is', 'dense.', 'Explicit', 'better', 'nested.', 'Complex', 'ugly.', 'Sparse', 'implicit.', 'complex.', 'than', 'complicated.']
假设inp是从文件中检索的

inp = """Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense."""


data = inp.splitlines()

print data

_d = {}

for line in data:
    word_lst = line.split()
    for word in word_lst:
        if word in _d:
            _d[word] += 1
        else:
            _d[word] = 1

print _d.keys()
输出

['Beautiful', 'Flat', 'Simple', 'is', 'dense.', 'Explicit', 'better', 'nested.', 'Complex', 'ugly.', 'Sparse', 'implicit.', 'complex.', 'than', 'complicated.']

使用当前代码,行:

lines = getty[lineNum]

应该在while循环中移动

使用当前代码,行:

lines = getty[lineNum]
应该在while循环中移动

我建议:

#!/usr/local/cpython-3.3/bin/python

import pprint
import collections

def genwords(file_):
    for line in file_:
        for word in line.split():
            yield word

def main():
    with open('gettysburg.txt', 'r') as file_:
        result = collections.Counter(genwords(file_))

    pprint.pprint(result)

main()
…但是您可以使用re.findall来更好地处理标点符号,而不是string.split。

我建议:

#!/usr/local/cpython-3.3/bin/python

import pprint
import collections

def genwords(file_):
    for line in file_:
        for word in line.split():
            yield word

def main():
    with open('gettysburg.txt', 'r') as file_:
        result = collections.Counter(genwords(file_))

    pprint.pprint(result)

main()

…但是您可以使用re.findall来更好地处理标点符号,而不是string.split。

在这里创建问题时,缩进是否正确,还是只是复制/粘贴问题?为什么需要将lineNum作为函数uniquify的参数?我使用lineNum是为了引用文件中的每一行。对于uniquify函数,我正在尝试将lineNum+=1与if语句一起放入uniquify函数中。您不会推进while循环,只会一直粘贴同一行,直到计数器命中20@turbo在意识到这个简单的错误后,刚刚修复了它,谢谢!在这里创建问题时,缩进是否正确,或者只是复制/粘贴问题?为什么需要lineNum作为函数uniquify的参数?我使用lineNum来引用文件中的每一行。对于uniquify函数,我正在尝试将lineNum+=1与if语句一起放入uniquify函数中。您不会推进while循环,只会一直粘贴同一行,直到计数器命中20@turbo在意识到这个简单的错误后,刚刚修复了它,谢谢@user3010284这是正确的答案,这就是为什么我投了更高的票,但你也应该看看我的答案。您使这项任务复杂化了。@user3010284这是正确的答案,这就是为什么我对它投了更高的票,但您也应该看看我的答案。你把这项任务复杂化了。