Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中读取文本文件并将其拆分为单个单词_Python_String_Split - Fatal编程技术网

在python中读取文本文件并将其拆分为单个单词

在python中读取文本文件并将其拆分为单个单词,python,string,split,Python,String,Split,我有一个由数字和单词组成的文本文件,例如-09807754 18 n 03贵族0蓝血0贵族,我想将它拆分,以便每个单词或数字都作为新行出现 一个空格分隔符将是理想的,因为我希望与破折号保持连接的话 这就是我到目前为止所做的: f = open('words.txt', 'r') for word in f: print(word) 我不太确定如何从这里开始,我希望这是输出: 09807754 18 n 3 aristocrat ... 给定此文件: $ cat words.txt l

我有一个由数字和单词组成的文本文件,例如-
09807754 18 n 03贵族0蓝血0贵族
,我想将它拆分,以便每个单词或数字都作为新行出现

一个空格分隔符将是理想的,因为我希望与破折号保持连接的话

这就是我到目前为止所做的:

f = open('words.txt', 'r')
for word in f:
    print(word)
我不太确定如何从这里开始,我希望这是输出:

09807754
18
n
3
aristocrat
...
给定此文件:

$ cat words.txt
line1 word1 word2
line2 word3 word4
line3 word5 word6
如果一次只需要一个单词(忽略文件中空格和换行符的含义):

印刷品:

line1
word1
word2
line2
...
word6 
类似地,如果要将文件转换为文件中单个单词的平面列表,可以执行以下操作:

with open('words.txt') as f:
    flat_list=[word for line in f for word in line.split()]

>>> flat_list
['line1', 'word1', 'word2', 'line2', 'word3', 'word4', 'line3', 'word5', 'word6']
它可以使用
print'\n.创建与第一个示例相同的输出。join(平面列表)

或者,如果要在文件的每一行中嵌套单词列表(例如,从文件创建行和列的矩阵):

如果您想要一个正则表达式解决方案,它允许您过滤
wordN
vs
lineN
在示例文件中键入单词:

import re
with open("words.txt") as f:
    for line in f:
        for word in re.findall(r'\bword\d+', line):
            # wordN by wordN with no lineN
或者,如果您希望它是带有正则表达式的逐行生成器:

 with open("words.txt") as f:
     (word for line in f for word in re.findall(r'\w+', line))

这是我完全实用的方法,它避免了阅读和拆分行。它利用模块:

注意:对于python 3,将
itertools.imap
替换为
map
示例用法:

>>> import sys
>>> for w in readwords(sys.stdin):
...     print (w)
... 
I really love this new method of reading words in python
I
really
love
this
new
method
of
reading
words
in
python
           
It's soo very Functional!
It's
soo
very
Functional!
>>>
我猜在您的情况下,这将是使用函数的方式:

with open('words.txt', 'r') as f:
    for word in readwords(f):
        print(word)
作为补充, 如果你正在读取一个VVVLY大文件,并且你不想一下子把所有内容读入内存,你可以考虑使用<强>缓冲区>,然后按收益率返回每个词:

def read_words(inputfile):
    with open(inputfile, 'r') as f:
        while True:
            buf = f.read(10240)
            if not buf:
                break

            # make sure we end on a space (word boundary)
            while not str.isspace(buf[-1]):
                ch = f.read(1)
                if not ch:
                    break
                buf += ch

            words = buf.split()
            for word in words:
                yield word
        yield '' #handle the scene that the file is empty

if __name__ == "__main__":
    for word in read_words('./very_large_file.txt'):
        process(word)

您可以使用nltk标记单词,然后将所有单词存储在一个列表中,下面是我所做的。 如果你不知道nltk;它代表自然语言工具包,用于处理自然语言。如果你想开始,这里有一些资源 [

输出将如下所示:

09807754
18
n
03
aristocrat
0
blue_blood
0
patrician
这是你文件中所有单词的列表

import re
with open(filename) as file:
    words = re.findall(r"([a-zA-Z\-]+)", file.read())

这些数据真的有引号吗?是
“09807754 18 n 03贵族0蓝血0贵族”
还是
09807754 18 n 03贵族0蓝血0贵族
在文件中?我用上面的注释跟进。这些数据真的有引号围绕着文件对象的可写性(
用于f:
)?@haccks:它是在文件上逐行循环的方法。另请参阅我只是想知道它背后的机制;它是如何工作的?
open
创建一个文件对象。Python文件对象支持文本文件的逐行迭代(二进制文件一次读取…)因此,
for
循环中的每个循环都是文本文件的一行。在文件末尾,file对象引发了
StopIteration
,我们就完成了对该文件的处理。对该机制的更多理解超出了我在注释中所能做的。您还可以加载到主内存中并使用“re”对于那些对性能感兴趣的人来说,这比itertools的答案快了一个数量级。为什么是10240?我假设字节数?那么大约10kb?缓冲区能有多大?如果我对性能感兴趣,缓冲区会更小或更大,但会更好?我很困惑,进程会做什么?它没有定义。。。
with open('words.txt', 'r') as f:
    for word in readwords(f):
        print(word)
def read_words(inputfile):
    with open(inputfile, 'r') as f:
        while True:
            buf = f.read(10240)
            if not buf:
                break

            # make sure we end on a space (word boundary)
            while not str.isspace(buf[-1]):
                ch = f.read(1)
                if not ch:
                    break
                buf += ch

            words = buf.split()
            for word in words:
                yield word
        yield '' #handle the scene that the file is empty

if __name__ == "__main__":
    for word in read_words('./very_large_file.txt'):
        process(word)
import nltk 
from nltk.tokenize import word_tokenize 
file = open("abc.txt",newline='')
result = file.read()
words = word_tokenize(result)
for i in words:
       print(i)
09807754
18
n
03
aristocrat
0
blue_blood
0
patrician
with open(filename) as file:
    words = file.read().split()
import re
with open(filename) as file:
    words = re.findall(r"([a-zA-Z\-]+)", file.read())