Skip to content

Instantly share code, notes, and snippets.

@rangercyh
Last active December 18, 2015 17:39
Show Gist options
  • Save rangercyh/5819770 to your computer and use it in GitHub Desktop.
Save rangercyh/5819770 to your computer and use it in GitHub Desktop.
a function to transform csv file to tab file
function split(str, splitor, nMatchModel)
splitor = splitor or ','
nMatchModel = nMatchModel or true
local strArray = {}
local nStart = 1
local splitorLen = string.len(splitor)
local index = string.find(str, splitor, nStart, nMatchModel)
while index do
strArray[#strArray + 1] = string.sub(str, nStart, index - 1)
nStart = index + splitorLen
index = string.find(str, splitor, nStart, nMatchModel)
end
strArray[#strArray + 1] = string.sub(str, nStart, string.len(str))
return #strArray, strArray
end
-- 去掉行首和行尾的双引号和单引号
function sf_trim(s)
local _, quotedPart = string.match(s, "([\"'])(.-)%1")
return quotedPart
end
function ArrToTabStr(tbStrArr, tbCol)
local szOutPut = ""
local nFirstLine = 1
for _, nCol in pairs(tbCol) do
if tbStrArr[nCol] ~= nil then
if nFirstLine == 1 then
szOutPut = szOutPut..sf_trim(tbStrArr[nCol])
nFirstLine = 0
else
szOutPut = szOutPut..'\t'..sf_trim(tbStrArr[nCol])
end
end
end
szOutPut = szOutPut..'\n'
return szOutPut
end
--[[
本来听取裴凯的意见,准备增加另外一个屏蔽列表的,但是这个工具只是自己用,麻烦只是一次,就不多余操心了。
]]
function fCsvToTabFile(szFilePath, tbSelCol)
--打开csv文件
local tbRet = {}
local hCsvFile = io.open(szFilePath)
if not hCsvFile then
print("打不开指定文件:", szFilePath)
return
end
--创建输出的tab文件
local hTabFile = io.open("weibo_award.txt", "w")
if not hTabFile then
print("无法创建输出文件")
return
end
local nLineNum = 0
while 1 do
line = hCsvFile:read("*l")
if not line then
break
end;
local strOutPut = ArrToTabStr(split(line), tbSelCol)
if strOutPut ~= "" then
hTabFile:write(strOutPut)
end
nLineNum = nLineNum + 1
end
hCsvFile:close()
hTabFile:close()
print("本次微博活动总计转盘次数:", nLineNum-1)
end
fCsvToTabFile("C:\\Users\\D15411\\Desktop\\奖励0523.csv", {1,3,2,5});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment