【发布时间】:2014-05-11 19:50:46
【问题描述】:
我正在尝试编写一个允许我从 URL 中删除某些元素的函数。这些 URL 存储在名为 Backlink_Test 的 CSV 中。我想遍历该 URL 列表中的每个项目,从 URL 中删除不需要的元素,然后将修改后的 URL 添加到新列表中,然后将其存储在名为 Cleaned_URLs 的新 CSV 中。
代码在我可以打开源文件、运行循环然后将结果存储在目标文件中的范围内工作。但是,我遇到了一个非常烦人的问题:在目标文件中,URL 存储 每个字符都在一个单独的单元格中,而不是整个 URL 在一个单元格中。
这让我感到惊讶,因为我做了一个小测试,我将内容从 CSV 复制到另一个(没有修改任何内容),并且具有多个字符的单词被存储得很好。所以我怀疑是for循环造成了问题?
任何帮助/见解将不胜感激!下面的代码,并附上目标文件的屏幕截图。
import csv
new_strings = []
#replace unwanted elements and add cleaned strings to new list
with open("Backlink_Test.csv", "rb") as csvfile:
reader = csv.reader(csvfile)
for string in reader:
string = str(string)
string = string.replace("www.", "").replace("http://", "").replace("https://", "")
new_strings.append(string)
new_strings.sort()
print new_strings #for testing only; will be removed once function is working
cleaned_file = open("Cleaned_URLS.csv", "w")
writer = csv.writer(cleaned_file)
writer.writerows(new_strings)
cleaned_file.close()
现在是工作代码:
import csv
new_strings = []
#replace unwanted elements and add cleaned strings to new list
with open("Backlink_Test.csv", "rb") as csvfile:
reader = csv.reader(csvfile)
for string in reader:
string = str(string)
string = string.replace("www.", "").replace("http://", "").replace("https://", "")
new_strings.append(string)
new_strings.sort()
print new_strings
cleaned_file = open("Cleaned_URLS.csv", "w")
writer = csv.writer(cleaned_file)
for url in new_strings:
writer.writerow([url])
cleaned_file.close()
【问题讨论】: