这段代码是用来自动重命名一堆被调用的CSV
文件
history (1) ... history (42)
以下是事件列表: https://drive.google.com/open?id=0B5bJvxM9TZkhYXZOSnRDVnhTbFk
以下是“我的文件夹”中文件的屏幕截图:
这些新名字是通过靓汤从网页中捕捉到的。新名称在格式上有两种可能大多数有two
节,只有四个有three
节。你知道吗
当谈到rename函数时,我遇到了一个error
。你知道吗
以下是全部代码:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import os
events = open('events.txt', 'r')
os.chdir("C:\\Users\\Sayed\\Downloads")
# name
for event in events:
sauce = urlopen(event).read()
soup = BeautifulSoup(sauce, 'lxml')
title = soup.find_all('title')
for x in title:
title = x.text
try:
firstName, lastNmame, country = (title.split('-'))
firstName = firstName.strip()
lastNmame = lastNmame.strip()
country = country.strip()
name = ('{} - {} - {}'.format(country, firstName, lastNmame))
for file in os.listdir():
firstName, ext = os.path.splitext(file)
os.rename(firstName, name)
except ValueError:
pass
try:
firstName, country = (title.split('-'))
firstName = firstName.strip()
country = country.strip()
name = ('{} - {}'.format(country, firstName))
for file in os.listdir():
firstName, ext = os.path.splitext(file)
os.rename(firstName, name)
except ValueError:
pass
错误如下:
Traceback (most recent call last):
File "C:/Users/Sayed/PycharmProjects/Tutorial/pan.py", line 37, in <module>
os.rename(firstName, name)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'history (1)' -> 'European Monetary Union - Services Sentiment'
起作用了!
我复制了您的整个设置,包括所有
history (x)
文件和所有内容,并设法编写了有效的代码。你知道吗在这里:
它是如何工作的?
首先,我们像以前一样
import
所有必要的libraries
。你知道吗然后我们打开包含所有
links
的events.txt
文件到我们想要提取titles
的页面。你知道吗然后我们进入主
for-loop
。我们在这里循环的内容可能看起来有点奇怪,如果你以前没有见过的话,从技术上讲,我们从events
中创建一个list
的tuples
,其中tuple
的第一个element
是index
,第二个element
是值,所以在这里,它是event
。举个例子让你完全理解这一点:所以现在,我们有两个
variables
要处理:在所有events
中的event
(因此link
到页面)和index
。请记住,由于Pythonlists
是基于0
的,index
将从0
到42
(而不是1
到43
),因此当我们稍后使用它重命名files
时,必须记住添加1
。你知道吗接下来,我们从
link
得到raw data
,也就是event
和urllib
。然后,我们使用BeautifulSoup
从event
中提取title
。这是通过查找页面中'title'
的所有并使用[0]
索引第一个来实现的。我们需要index
像这样soup.find_all
返回长度list
1
的element
。然后我们用这个的.text
得到一个string
,然后在string
上做一个.strip()
,去掉回车符和换行符(/r/n
)。你知道吗接下来,我们定义一个名为
variable
的filename
,它将存储我们当前想要rename
的file
的名称。我们得到name
的方法是简单地取history (x).csv
位,它对于所有的files
都是相同的,并用我们正在处理的当前event
(file
)的format
位格式化,而不是i
位作为files
开始于history (1).csv
而不是history (0).csv
。你知道吗然后我们定义一个名为
newName
的变量,它就是我们想要rename
的filename
。这个名字就是我们之前提取的name
(Thetitle
),然后在末尾提取'.csv'
,因为我们需要保持file
extensions
不变。你知道吗最后,我们为这个
file
调用rename
。这只是filename
到newName
之间的关系!你知道吗这肯定对我有用,所以我看不出有什么理由不适合你。。。另外,我希望你能理解代码正在做的每件事,只要在评论中问我是否遗漏了什么。。。你知道吗
相关问题 更多 >
编程相关推荐