【发布时间】:2015-11-10 18:27:32
【问题描述】:
我有一个从 millercenter.org 抓取语音并返回处理后的语音的功能。然而,我的每一篇演讲的开头都有“成绩单”这个词(这就是它被编码到 HTML 中的方式)。所以,我所有的文本文件都是这样的:
\n <--- there's really just a new line, here, not literally '\n'
transcript
fourscore and seven years ago, blah blah blah
我将这些文件保存在我的 U:/ 驱动器中 - 我如何遍历这些文件并删除“成绩单”?这些文件基本上是这样的:
编辑:
speech_dict = {}
for filename in glob.glob("U:/FALL 2015/ENGL 305/NLP Project/Speeches/*.txt"):
with open(filename, 'r') as inputFile:
filecontent = inputFile.read();
filecontent.replace('transcript','',1)
speech_dict[filename] = filecontent # put the speeches into a dictionary to run through the algorithm
这并没有改变我的演讲。 “成绩单”还在。
我也尝试将它放入我的文本处理函数中,但这也不起作用:
def processURL(l):
open_url = urllib2.urlopen(l).read()
item_soup = BeautifulSoup(open_url)
item_div = item_soup.find('div',{'id':'transcript'},{'class':'displaytext'})
item_str = item_div.text.lower()
item_str_processed = punctuation.sub(' ',item_str)
item_str_processed_final = item_str_processed.replace('—',' ').replace('transcript','',1)
splitlink = l.split("/")
president = splitlink[4]
speech_num = splitlink[-1]
filename = "{0}_{1}".format(president, speech_num)
return filename, item_str_processed_final # giving back filename and the text itself
这是我通过processURL 运行的示例网址:http://millercenter.org/president/harding/speeches/speech-3805
【问题讨论】:
-
使用
f.read()将每个文件读入一个字符串,然后像@Will所说的replace或使用data.strip()[len('transcript'):]对数据进行切片,然后使用'w'参数写回同一个文件以覆盖现有文件 -
GBR24,完全不清楚这其中的哪一部分给您带来了麻烦。您是在问如何创建 Python 程序、如何执行 Python 程序、如何进行文件 i/o、如何编写
for循环,或者如何从字符串中删除子字符串?不要回答这个反问:相反,开始自己编写脚本。当您走到死胡同时,请向我们展示您所做的事情并提出更具体的问题。 -
@RNar 很好的切片调用,我想也可以是
data = data.split()[1:]这虽然删除了第一个单词(不管它是什么),所以任何格式错误的文件都会变得更加格式错误。 -
这绝对比直弦切片更干净
-
看到您的编辑,
.replace方法返回您的字符串的副本。因为字符串是不可变的,所以不能在其中进行就地替换。重新分配文件内容,例如filecontents = filecontents.replace(...)