根据冒号分割出星座和运势信息列表,将每 行数据依次存入列表 txt 中,使 txt[0]为星座,txt[1]中存储的是运势
时间: 2023-06-08 18:06:08 浏览: 77
答案:
好的,让我来帮你实现这个功能。你可以按照以下代码进行操作:
```python
# 假设有一个字符串 s,包含星座和运势信息
s = "水瓶座:今天幸运数字为7,工作运势佳。"
# 使用冒号分割字符串,得到一个列表 txt
txt = s.split(":")
# 打印分割后的列表
print(txt)
# 输出结果为:['水瓶座', '今天幸运数字为7,工作运势佳。']
# 将列表中的运势信息再次分割,得到一个列表 fortune
fortune = txt[1].split(",")
# 打印分割后的运势信息
print(fortune)
# 输出结果为:['今天幸运数字为7', '工作运势佳。']
# 将txt列表中的元素依次存入新的列表 info 中
info = []
info.extend(txt)
info.extend(fortune)
# 打印最终得到的列表
print(info)
# 输出结果为:['水瓶座', '今天幸运数字为7,工作运势佳。', '今天幸运数字为7', '工作运势佳。']
```
这样,你就可以实现根据冒号分割出星座和运势信息列表,并将每行数据依次存入列表 txt 中。如果你有其他问题,可以随时问我哦!
相关问题
设计程序,读取“xingzuo.txt”中的星座文字信息,根据冒号进行字符串分割,将 分割后的文字以列表方式打印出来
with open("xingzuo.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
for line in lines:
info = line.strip().split(":")
print(info)
循环删除某文件夹中所有txt文件中每一行冒号前面的数据
可以使用以下代码实现:
```lua
local function removeDataBeforeColon(filename)
local file = io.open(filename, "r")
local lines = {}
for line in file:lines() do
table.insert(lines, string.sub(line, string.find(line, ":") + 1))
end
file:close()
file = io.open(filename, "w")
for _, line in ipairs(lines) do
file:write(line .. "\n")
end
file:close()
end
local function removeColonDataInFolder(folder)
for file in lfs.dir(folder) do
if file ~= "." and file ~= ".." then
local filename = folder .. "/" .. file
local attr = lfs.attributes(filename)
if attr.mode == "file" and string.sub(file, -4) == ".txt" then
removeDataBeforeColon(filename)
elseif attr.mode == "directory" then
removeColonDataInFolder(filename)
end
end
end
end
removeColonDataInFolder("folder_path")
```
其中,`removeDataBeforeColon` 函数用于删除某个文件中每一行冒号前面的数据,`removeColonDataInFolder` 函数用于循环删除某文件夹中所有 txt 文件中每一行冒号前面的数据。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)