如何使用python通过拾取某些部分将文本文件读入csv
我有一个文本文件,看起来像这样: 当前职务:如何使用python通过拾取某些部分将文本文件读入csv,python,python-2.7,text,Python,Python 2.7,Text,我有一个文本文件,看起来像这样: 当前职务: 仪表工程师 当前工资: 30000英镑 经验: 2年 所需位置: 未提供 所需职务: 智能仪表工程师 期望工资: 30000英镑 工作类型: 永久性|合同|临时 当前职务: 双燃料智能仪表工程师 当前工资: 30000英镑 经验: 4年 所需位置: 未提供 所需职务: 未提供 期望工资: 34999英镑 工作类型: 永久性|合同|临时 每行用新行拆分,数据集用空格分隔 我想使用python来提取标题下的数据。如: 现任职务: 仪表工程师 将进入“当前
仪表工程师
当前工资:
30000英镑
经验:
2年
所需位置:
未提供
所需职务:
智能仪表工程师
期望工资:
30000英镑
工作类型:
永久性|合同|临时
当前职务:
双燃料智能仪表工程师
当前工资:
30000英镑
经验:
4年
所需位置:
未提供
所需职务:
未提供
期望工资:
34999英镑
工作类型:
永久性|合同|临时
每行用新行拆分,数据集用空格分隔 我想使用python来提取标题下的数据。如: 现任职务: 仪表工程师 将进入“当前职务”列。然后拿下一组,把它们放在下一行 如何使用python实现这一点 我是python新手。我所能做的就是读取文件。使用IF选择数据不起作用
f = open("test.txt", "r")
lines = f.readlines()
for line in lines:
print(line)
在将数据转换为
csv
格式之前,首先需要重新构造数据
试试这个:
import csv
from collections import OrderedDict
with open('data.txt', 'r') as data, open('output.csv', 'w') as file:
rows = data.read().split('\n\n')
output = [
OrderedDict(
(k.rstrip(':'), v) for k, v in zip(row.split('\n')[::2], row.split('\n')[1::2])
)
for row in rows
]
writer = csv.DictWriter(file, fieldnames=output[0].keys(), lineterminator='\n')
writer.writeheader()
writer.writerows(output)
输出:
Current job title,Current salary,Experience,Desired location,Desired job title,Desired salary,Job Type
meter engineer,"£30,000",2 years,Not supplied,smart meter engineer,"£30,000",Permanent | Contract | Temp
dual fuel smart meter engineer,"£30,000",4 years,Not supplied,Not supplied,"£34,999",Permanent | Contract | Temp
注意:您需要使用OrderedDict
,因为python 2.7上没有对字典对象进行排序,这会给您的csv
文件带来麻烦。相关的伪OrderedDict
理解受到以下答案的启发:
作为旁注,Python2.7正在逐渐过时。你真的应该考虑把你的项目转移到Python 3 .x Base.< /P> < p>这个代码是基本的,但它可能只是个诀窍。它所做的只是读取找到的一行,该行上有数据。它知道哪一行是开着的,因为它准确地假设了这个例子
f = open("test.txt", "r")
if f.mode == 'r':
repeat = f.find('Current job title:') #this give how many times 'Current job title is found in the program'
while repeat >= 1:
repeat = repeat - 1 #changes repeat by -1 every time you do this counting how many times you run this loop
print("Job Title:") #Finds and sets JobTitle to the title of job stated
JobTitle = f.readline(repeat * 15 - 13)
print(JobTitle) #Prints Job Title
print("Current salary:") #Repeat from Above
Pay = f.readline(repeat * 15 - 11)
print(Pay)
这只是将所有数据放在一个数组中。不是用夹板固定在新的线路上吗?谢谢。这是完美的,你发现答案是有用的,考虑投票或接受答案,以帮助未来的访客突出解决方案。但这完全取决于你:)
f = open("test.txt", "r")
if f.mode == 'r':
repeat = f.find('Current job title:') #this give how many times 'Current job title is found in the program'
while repeat >= 1:
repeat = repeat - 1 #changes repeat by -1 every time you do this counting how many times you run this loop
print("Job Title:") #Finds and sets JobTitle to the title of job stated
JobTitle = f.readline(repeat * 15 - 13)
print(JobTitle) #Prints Job Title
print("Current salary:") #Repeat from Above
Pay = f.readline(repeat * 15 - 11)
print(Pay)