2011-10-18 92 views
4

最近我一直在嘗試使用簡單的腳本來將點雲數據重命名爲工作格式。底部的代碼工作正常,我不知道我做錯了什麼。爲什麼不在for循環中工作?它將它添加到列表中,但它沒有被替換函數格式化。對不起,我知道這不是一個調試器,但我真的被困在這,它可能需要2秒鐘讓其他人看到這個問題。在for循環中運行replace()方法?

# Opening and Loading the text file then sticking its lines into a list [] 
filename = "/Users/sacredgeometry/Desktop/data.txt" 
text = open(filename, 'r') 
lines = text.readlines() 
linesNew = [] 
temp = None 


# This bloody for loop is the problem 
for i in lines: 
    temp = str(i) 
    temp.replace(' ', ', ',2) 
    linesNew.append(temp) 


# DEBUGGING THE CODE  
print(linesNew[0]) 
print(linesNew[1]) 

# Another test to check that the replace works ... It does! 
test2 = linesNew[0].replace(' ', ', ',2) 
test2 = test2.replace('\t', ', ') 
print('Proof of Concept: ' + '\n' + test2) 


text.close() 

回答

4

您沒有將返回值replace()分配給任何東西。此外,readlinesstr(i)是不必要的。

試試這個:

filename = "/Users/sacredgeometry/Desktop/data.txt" 
text = open(filename, 'r') 
linesNew = [] 

for line in text: 
    # i is already a string, no need to str it 
    # temp = str(i) 

    # also, just append the result of the replace to linesNew: 
    linesNew.append(line.replace(' ', ', ', 2)) 

# DEBUGGING THE CODE     
print(linesNew[0]) 
print(linesNew[1]) 

# Another test to check that the replace works ... It does! 
test2 = linesNew[0].replace(' ', ', ',2) 
test2 = test2.replace('\t', ', ') 
print('Proof of Concept: ' + '\n' + test2) 

text.close() 
+0

我愛你,我不能相信我沒有看到, :),演員只是其中一件嘗試的事情。這是漫長的一天:)非常感謝你。 – SacredGeometry

+0

@SacredGeometry Np樂於幫助:)。 – chown

3

字符串是不可改變的。 replace返回一個新的字符串,這是你必須插入linesNew列表。

# This bloody for loop is the problem 
for i in lines: 
    temp = str(i) 
    temp2 = temp.replace(' ', ', ',2) 
    linesNew.append(temp2) 
0

我有一個類似的問題,並提出了下面的代碼來幫助解決它。我的具體問題是我需要用相應的標籤替換字符串的某些部分。我也希望能在我的應用程序的不同地方重用。

與下面的代碼,我能夠做到以下幾點:

>>> string = "Let's take a trip to Paris next January" 
>>> lod = [{'city':'Paris'}, {'month':'January'}] 
>>> processed = TextLabeler(string, lod) 
>>> processed.text 
>>> Let's take a trip to [[ city ]] next [[ month ]] 

這裏的所有代碼:

class TextLabeler(): 
    def __init__(self, text, lod): 
     self.text = text 
     self.iterate(lod) 

    def replace_kv(self, _dict): 
     """Replace any occurrence of a value with the key""" 

     for key, value in _dict.iteritems(): 
      label = """[[ {0} ]]""".format(key) 
      self.text = self.text.replace(value, label) 
      return self.text 

    def iterate(self, lod): 
     """Iterate over each dict object in a given list of dicts, `lod` """ 

     for _dict in lod: 
      self.text = self.replace_kv(_dict) 
     return self.text