Skip to main content
 首页 » 编程设计

python之rstrip() 没有按预期工作

2025年05月04日13rubylouvre

我写了以下 python 代码。我期望它做的是将文件“噪声”中的一个随机词添加到“原始”的每一行并将其打印到文件“数据集”

#! /usr/bin/python 
 
from random import randint 
 
raw = open("raw_dataset_1", "r") 
noise = open("random", "r") 
dataset = open("raw_noisy", "w") 
 
lines = noise.readlines() 
 
for line in raw: 
    a = randint(1, 5449) 
    addNoise = lines[a-1] 
    #print a 
    #print addNoise 
    noisy = (line + addNoise) 
    noisy1= noisy.rstrip() 
    #print noisy1 
    dataset.write(noisy1) 

我预期的“数据集”文件是:

city mountain sky sun chalk 
bay lake sun tree discussions 
beach sea sky sun background 

但我得到:

city mountain sky sun  
chalk 
bay lake sun tree  
discussions 
beach sea sky sun  
background 

有人可以指出我的错误吗?

请您参考如下方法:

我想你想做 noisy = (line.rstrip("\n") + ""+ addNoise)

我测试了它,它对我有用。