python - 将所有并排单词成对拆分字符串单词

标签 python

<分区>

我需要将字符串拆分成单词,然后将每个连续的单词成对连接起来,如下所示:

"This is my subject string"  

会去:

"This is"    
"is my"  
"my subject"  
"subject string" 

字符串的长度从 5 个单词到 250 个单词不等。此外,它会在大量数据(1GB 左右)上执行此操作。在 Python 中有没有一种有效的方法来做到这一点?

我看到很多关于哪种方法最有效的建议,所以想先问问。

最佳答案

您可以使用 split 方法和列表理解来做到这一点:

text = "This is my subject string"
words = text.split() #note that split without arguments splits on whitespace
pairs = [words[i]+' '+words[i+1] for i in range(len(words)-1)]
print(pairs)

关于python - 将所有并排单词成对拆分字符串单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16126122/

相关文章:

python - 如何在不连接的情况下读取 Python 数据框中的数据?

python - 使用 str.contains 时如何忽略带有掩码的行?

python - 如何使用 Flask 通过 HTML 表单携带带空格的字符串

python - 非递归函数 follow_me(d, s) 其中 d 是字典,s 是字符串

python - 如何将列表/字典转换为数据框?

python - Brython 中的 super().__str__() 应该返回不同的东西吗?

python - 使用python从云存储桶下载文件时如何显示进度条

python 2.7 : how to read only a few lines at a time from a file?

Python/Pandas - 查询多索引列

python - 如何将嵌套字典转换为Python元组?