python - 文本合并 - 如何在 Python 中执行此操作? (R源)

标签 python r text

我尝试了几种方法,但没有一个能将其转换为 Python,特别是因为我遇到了这个错误:

'str' object does not support item assignment

R 可以使用以下代码执行相同的操作:

f<-0
text<- c("foo", "btextr", "cool", "monsttex")
for (i in 1:length(text)){
    f[i]<-paste(text[i],text[i+1], sep = "_")
}
f

输出为:

"foo_btextr"    "btextr_cool"   "cool_monsttex" "monsttex_NA"

如果您能帮助我为 Python 做同样的事情,我将不胜感激。谢谢。

最佳答案

在 R 中,你的输出将是(下次请将其放入问题中):

> f
[1] "foo_btextr"    "btextr_cool"   "cool_monsttex" "monsttex_NA"

在 Python 中 strings are immutable 。因此,您需要创建新字符串,例如:

new_strings = []
text = ['foo', 'btextr', 'cool', 'monsttex']
for i,t in enumerate(text):
  try: 
    new_strings.append(text[i] + '_' + text[i+1])
  except IndexError:
    new_strings.append(text[i] + '_NA')

结果是:

>>> new_strings
['foo_btextr', 'btextr_cool', 'cool_monsttex', 'monsttex_NA']

关于python - 文本合并 - 如何在 Python 中执行此操作? (R源),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35006131/

相关文章:

powershell - 使用 PowerShell 在长文本文件的顶部插入一行文本

python - 在 Python 中实现存储库模式?

python - 如何从管理面板的字段中提取信息?

python - balance() 方法在 python 中调用时不起作用

r - 在 R 中生成满足约束的随机数

c# - 如何使用颜色对话框仅将颜色应用于 C# 中的选定文本

python - 如何解决 : InvalidArgumentError: Graph execution error?

r - R-CSV错误-意外的数字常量

在 Windows 中从 cmd 运行 R

php - 在文本文件中转换 "enter"in\n