【发布时间】:2013-11-02 08:30:26
【问题描述】:
我正在尝试使用 regex 模块编写一小段代码,该模块将从 .csv 文件中删除部分 url 并将选定的块作为输出返回。如果该部分以 .com/go/ 结尾,我希望它在“go”之后返回内容。代码如下:
import csv
import re
with open('rtdata.csv', 'rb') as fhand:
reader = csv.reader(fhand)
for row in reader:
url=row[6].strip()
section=re.findall("^http://www.xxxxxxxxx.com/(.*/)", url)
if section==re.findall("^go.*", url):
section=re.findall("^http://www.xxxxxxxxx.com/go/(.*/)", url)
print url
print section
这里有一些示例输入输出:
- 示例 1
- 输入:
http://www.xxxxxxxxx.com/go/news/videos/ - 输出:
news/videos
- 输入:
- 示例 2
- 输入:
http://www.xxxxxxxxx.com/new-cars/ - 输出:
new-cars
- 输入:
我在这里错过了什么?
【问题讨论】:
-
一个包含不同列的 csv 文件。我要读取的列位于 python 读取的字符串的位置 [6]。
-
我的 Python 不是很流利,但似乎 "if section==re.findall("^go.*", url):" 行实际上与原始 url 匹配,不是在上一行找到的子部分。