将字符串拆分为固定长度的块并在 Python 中使用它们的最佳方法是什么? [英] What's the best way to split a string into fixed length chunks and work with them in Python?

查看:65
本文介绍了将字符串拆分为固定长度的块并在 Python 中使用它们的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下方法从文本文件中读取一行内容:

 file = urllib2.urlopen("http://192.168.100.17/test.txt").read().splitlines()

并在 telnetlib.write 命令中将其输出到 16 个字符宽的 LCD 显示器.如果读取的行超过 16 个字符,我想将其分解为 16 个字符长的字符串部分,并在一定延迟(例如 10 秒)后推出每个部分,完成后代码应移至下一行输入文件并继续.

我已经尝试搜索各种解决方案并阅读 itertools 等,但我对 Python 的理解还不足以让任何事情正常工作,而无需使用混乱的 if then else 语句以冗长的方式进行操作这可能会让我束手无策!

对我来说,做我想做的事最好的方式是什么?

解决方案

一个解决方案是使用这个函数:

def chunkstring(string, length):return (string[0+i:length+i] for i in range(0, len(string), length))

这个函数返回一个生成器,使用生成器推导式.生成器返回切片后的字符串,从 0 + 块长度的倍数,到块长度 + 块长度的倍数.

您可以像列表、元组或字符串一样迭代生成器 - for i in chunkstring(s,n):,或使用 list(generator) 将其转换为列表(例如).生成器比列表更节省内存,因为它们会根据需要生成元素,而不是一次性生成所有元素,但是它们缺少索引等某些功能.

这个生成器最后还包含任何较小的块:

<预><代码>>>>列表(块串(abcdefghijklmnopqrstuvwxyz",5))['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy', 'z']

示例用法:

text = """这是第一行.这是第二行.下面这行是真的.上面那行是假的.一条短线.一条非常非常非常非常非常非常非常长的队伍.自参考线.最后一行."""lines = (i.strip() for i in text.splitlines())对于线中线:对于块串中的块(第 16 行):打印(块)

I am reading in a line from a text file using:

   file = urllib2.urlopen("http://192.168.100.17/test.txt").read().splitlines()

and outputting it to an LCD display, which is 16 characters wide, in a telnetlib.write command. In the event that the line read is longer than 16 characters I want to break it down into sections of 16 character long strings and push each section out after a certain delay (e.g. 10 seconds), once complete the code should move onto the next line of the input file and continue.

I've tried searching various solutions and reading up on itertools etc. but my understanding of Python just isn't sufficient to get anything to work without doing it in a very long winded way using a tangled mess of if then else statements that's probably going to tie me in knots!

What's the best way for me to do what I want?

解决方案

One solution would be to use this function:

def chunkstring(string, length):
    return (string[0+i:length+i] for i in range(0, len(string), length))

This function returns a generator, using a generator comprehension. The generator returns the string sliced, from 0 + a multiple of the length of the chunks, to the length of the chunks + a multiple of the length of the chunks.

You can iterate over the generator like a list, tuple or string - for i in chunkstring(s,n): , or convert it into a list (for instance) with list(generator). Generators are more memory efficient than lists because they generator their elements as they are needed, not all at once, however they lack certain features like indexing.

This generator also contains any smaller chunk at the end:

>>> list(chunkstring("abcdefghijklmnopqrstuvwxyz", 5))
['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy', 'z']

Example usage:

text = """This is the first line.
           This is the second line.
           The line below is true.
           The line above is false.
           A short line.
           A very very very very very very very very very long line.
           A self-referential line.
           The last line.
        """

lines = (i.strip() for i in text.splitlines())

for line in lines:
    for chunk in chunkstring(line, 16):
        print(chunk)

这篇关于将字符串拆分为固定长度的块并在 Python 中使用它们的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆