鱼C论坛

 找回密码
 立即注册
查看: 2434|回复: 13

[已解决]求助!关于如何分割string再替换

[复制链接]
发表于 2017-4-24 14:35:47 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
如果我有一个txt文件
比如 num.txt
里面的数是
1,2,3,4
1,,1,2
哈哈哈你删了我吧
2, ,3,

我要做的是,定义一个函数
1.两个连续逗号之前的数默认为0
2.删掉文字
3.两个逗号中有空格也默认为1

最后这组数变成
1,2,3,4
1,0,1,2
2,0,3,0

求解

比如我定义一个函数
def getPapers(y):   #先读文件
    a = open('papers.txt','r')
   # for line in a:
#       print(line[:-1])
         x = a(i);
        def parseVote(s):   #具体的操作  求解 不会做
            for i in a:
                if(len(x)==0):
                    return 0
                elif(a(i)>0)
                    return a(i)
                else
                    return -1
            
最佳答案
2017-4-24 16:45:58
本帖最后由 gopythoner 于 2017-4-24 16:47 编辑
gopythoner 发表于 2017-4-24 16:28
数字变化的部分可以这样写

删除文字的部分其实要看你的数据格式,如果没有文字的部分是只有数字的话,那 ...


完整的函数我分成2个部分
  1. def change(astr):
  2.   newlis = []
  3.   lis = astr.split(",")
  4.   for each in lis:
  5.     if each == "" or each == " ":
  6.       newlis.append(0)
  7.     else:
  8.       newlis.append(int(each))
  9.   print(newlis)
  10.   return newlis

  11. def delstr(filename):
  12.   thelist = []
  13.   with open(filename,"r") as f:
  14.     lines = f.readlines()
  15.   for line in lines:
  16.     k = line.replace(",","").replace(" ","")
  17.     try:
  18.       if int(k):
  19.         thelist.append(line)
  20.     except:
  21.       pass
  22.   return thelist

  23. lis = delstr(filename)
  24. for each in lis:
  25.   change(each)
复制代码


比如你的文件名称是“test.txt”
那filename就是这个
这2个函数就能得到你要的结果,打印数字,有文字的都删除不要
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-4-24 16:28:17 | 显示全部楼层
数字变化的部分可以这样写
  1. def change(astr):
  2.   newlis = []
  3.   lis = astr.split(",")
  4.   for each in lis:
  5.     if each == "" or each == " ":
  6.       newlis.append(0)
  7.     else:
  8.       newlis.append(int(each))
  9.   print(newlis)

  10. a = "1, ,1,2"
  11. b = "1,,3,"
  12. change(a)
  13. change(b)
  14. >>>[1, 0, 1, 2]
  15. >>>[1, 0, 3, 0]
复制代码

删除文字的部分其实要看你的数据格式,如果没有文字的部分是只有数字的话,那就好办,如果有的是又有文字又有数字,那就复杂了,要考虑的判断条件会变多
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-4-24 16:45:58 | 显示全部楼层    本楼为最佳答案   
本帖最后由 gopythoner 于 2017-4-24 16:47 编辑
gopythoner 发表于 2017-4-24 16:28
数字变化的部分可以这样写

删除文字的部分其实要看你的数据格式,如果没有文字的部分是只有数字的话,那 ...


完整的函数我分成2个部分
  1. def change(astr):
  2.   newlis = []
  3.   lis = astr.split(",")
  4.   for each in lis:
  5.     if each == "" or each == " ":
  6.       newlis.append(0)
  7.     else:
  8.       newlis.append(int(each))
  9.   print(newlis)
  10.   return newlis

  11. def delstr(filename):
  12.   thelist = []
  13.   with open(filename,"r") as f:
  14.     lines = f.readlines()
  15.   for line in lines:
  16.     k = line.replace(",","").replace(" ","")
  17.     try:
  18.       if int(k):
  19.         thelist.append(line)
  20.     except:
  21.       pass
  22.   return thelist

  23. lis = delstr(filename)
  24. for each in lis:
  25.   change(each)
复制代码


比如你的文件名称是“test.txt”
那filename就是这个
这2个函数就能得到你要的结果,打印数字,有文字的都删除不要
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-4-25 13:46:56 | 显示全部楼层
gopythoner 发表于 2017-4-24 16:28
数字变化的部分可以这样写

删除文字的部分其实要看你的数据格式,如果没有文字的部分是只有数字的话,那 ...

哈哈 可以加个QQ 或者微信好友吗?  
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-4-25 14:00:00 | 显示全部楼层
gopythoner 发表于 2017-4-24 16:28
数字变化的部分可以这样写

删除文字的部分其实要看你的数据格式,如果没有文字的部分是只有数字的话,那 ...

哦 对了 还有一个问题, 就是如果为负数,就返回 -1;

我是在if else 中加一个elif each <0 return -1吗?
可是感觉不对,这个是字符串吧 没法对比吧/
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-4-25 14:20:02 | 显示全部楼层
Jc嘻嘻 发表于 2017-4-25 14:00
哦 对了 还有一个问题, 就是如果为负数,就返回 -1;

我是在if else 中加一个elif each

把这句改一下就行了
  1. newlis.append(int(each))
复制代码

改成这样
  1. newlis.append(int(each) if int(each)>=0 else -1)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-4-25 14:21:45 | 显示全部楼层
Jc嘻嘻 发表于 2017-4-25 13:46
哈哈 可以加个QQ 或者微信好友吗?

我也是新手Python,只会一点点爬虫
只是基础可能比你好一点,你加我也没用
有问题可以直接发到论坛提问,自然有人给你解答
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-4-25 16:20:43 | 显示全部楼层
gopythoner 发表于 2017-4-25 14:21
我也是新手Python,只会一点点爬虫
只是基础可能比你好一点,你加我也没用
有问题可以直接发到论坛提问 ...

哎,我确实卡住了,身边也没有人可以给我讲一下的
你看。   下面这三个就是我这个问题原题的一部分, 这三个funtion是一个call一个的,我有点搞不清这个逻辑联系。 我不知道你英文如何 我注释一下.

1.
#这个function返回0如何参数是空, 返回-1如果参数不是数字(比如sdadas,下面有列子)返回本身如果是>0的整数,这个你上面已经回答我了,问题就是下面2个方程我应该怎么写

def parseVote(s):
parseVote(s) returns the vote from s. Return 0 for an empty vote, and -1 if there are any non-digits (other than spaces). For example,
parseVote("") = parseVote(" ") = 0,
parseVote("-3") = parseVote("no") = parseVote("1 5") = -1,
parseVote("15") = parseVote(" 15 ") = 15.

2. #参数s是投票结果(一组数列,就像我之前给你那个例子,'1,,2'  '2,3,4' 这种), n是三个候选人。
如果参数s里面的数组是正常的,比如是'1,2,3'就返回本身,如果有问题,比如有空格,有字母,或者其他问题,只要不是完整的三个数, 就返回(例子下面)。
def parsePaper(s, n):
parsePaper(s, n) returns the votes from the ballot paper s in an election with n candidates, plus an error message if appropriate. If s is formal, return the list of numbers found in s and the empty string; if s is informal, return an empty list of numbers and the appropriate string below.
For example:
parsePaper("14, , 2", 4) = ([14, 0, 2], ""),
parsePaper(", , ", 4) = parsePaper("0, 0", 4) = ([ ], "blank"),
parsePaper("4, -8, 0", 4) = parsePaper("4, 7.8, 0", 4) = parsePaper("pointless, 5, 5", 4) = ([ ], "non-digits"),
parsePaper("1,2,,4,5", 4) = ([ ], "too long").

parsePaper will use parseVote.

# 第三个又用到了参数f ,,我真的有点搞不懂这个逻辑了。
def getPapers(f, n):
getPapers(f, n) returns a list containing the ballot papers from the file f, in an election with n candidates. Treat each line of the file as a separate paper. If f doesn't exist, print an appropriate error message and return the empty list. For example:
getPapers("smallfile.txt", 4) = [([1, 2, 3, 4], ""), ([], "blank"), ([0, 23, 0], ""), ([], "non-digits"), ([], "non-digits"), ([4,0,4,4], ""), ([], "too long"), ([], "blank")].
smallfile.txt is available from the project web-site.

getPapers will use parsePaper.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-4-25 16:25:14 | 显示全部楼层
gopythoner 发表于 2017-4-25 14:21
我也是新手Python,只会一点点爬虫
只是基础可能比你好一点,你加我也没用
有问题可以直接发到论坛提问 ...

哎,我确实卡住了,身边也没有人可以给我讲一下的
你看。   下面这三个就是我这个问题原题的一部分, 这三个funtion是一个call一个的,我有点搞不清这个逻辑联系。 我不知道你英文如何 我注释一下.

1.
#这个function返回0如何参数是空, 返回-1如果参数不是数字(比如sdadas,下面有列子)返回本身如果是>0的整数,这个你上面已经回答我了,问题就是下面2个方程我应该怎么写

def parseVote(s):
parseVote(s) returns the vote from s. Return 0 for an empty vote, and -1 if there are any non-digits (other than spaces). For example,
parseVote("") = parseVote(" ") = 0,
parseVote("-3") = parseVote("no") = parseVote("1 5") = -1,
parseVote("15") = parseVote(" 15 ") = 15.

2. #参数s是投票结果(一组数列,就像我之前给你那个例子,'1,,2'  '2,3,4' 这种), n是三个候选人。
如果参数s里面的数组是正常的,比如是'1,2,3'就返回本身,如果有问题,比如有空格,有字母,或者其他问题,只要不是完整的三个数, 就返回(例子下面)。
def parsePaper(s, n):
parsePaper(s, n) returns the votes from the ballot paper s in an election with n candidates, plus an error message if appropriate. If s is formal, return the list of numbers found in s and the empty string; if s is informal, return an empty list of numbers and the appropriate string below.
For example:
parsePaper("14, , 2", 4) = ([14, 0, 2], ""),
parsePaper(", , ", 4) = parsePaper("0, 0", 4) = ([ ], "blank"),
parsePaper("4, -8, 0", 4) = parsePaper("4, 7.8, 0", 4) = parsePaper("pointless, 5, 5", 4) = ([ ], "non-digits"),
parsePaper("1,2,,4,5", 4) = ([ ], "too long").

parsePaper will use parseVote.

# 第三个又用到了参数f ,,我真的有点搞不懂这个逻辑了。
def getPapers(f, n):
getPapers(f, n) returns a list containing the ballot papers from the file f, in an election with n candidates. Treat each line of the file as a separate paper. If f doesn't exist, print an appropriate error message and return the empty list. For example:
getPapers("smallfile.txt", 4) = [([1, 2, 3, 4], ""), ([], "blank"), ([0, 23, 0], ""), ([], "non-digits"), ([], "non-digits"), ([4,0,4,4], ""), ([], "too long"), ([], "blank")].
smallfile.txt is available from the project web-site.

getPapers will use parsePaper.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-4-25 17:01:05 | 显示全部楼层
本帖最后由 gopythoner 于 2017-4-25 17:04 编辑

我不是很明白,第二个函数为什么要附带 ([ ], "blank")这个后面的“blank”,这个算是一种表示数据状态的标识,你的问题应该是重在于处理数据,那直接按照要求处理数据就行了,干嘛要保留这种状态表示信息?
如果不需要这种状态信息的话,那第二个函数就会简单多了,只需要分是不是数字就行了
还有你第二个函数里面n=4这个不对吧,数据里面只有3个投票,应该n=3才对.第三个函数里面n才是等于4
这个n是直接决定了怎么判断数据是否合格的依据
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-4-25 17:08:08 | 显示全部楼层
Jc嘻嘻 发表于 2017-4-25 16:25
哎,我确实卡住了,身边也没有人可以给我讲一下的
你看。   下面这三个就是我这个问题原题的一部分,  ...

还有这一个我没看懂parsePaper("4, -8, 0", 4) = parsePaper("4, 7.8, 0", 4) = parsePaper("pointless, 5, 5", 4) = ([ ], "non-digits"),
这句的意思应该是如果数据中有负数,那就是不合格是数据,所以得到一个空列表
问题是,这中间的转换过程是依据什么?-8变成7.8是什么意思,之后又变成"pointless, 5, 5"是怎么变的?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-4-25 17:53:49 | 显示全部楼层
gopythoner 发表于 2017-4-25 17:08
还有这一个我没看懂parsePaper("4, -8, 0", 4) = parsePaper("4, 7.8, 0", 4) = parsePaper("pointless,  ...

我之前问的问题都是片段,我整体说一下把。  
这个的原因是 无论是小数还是负数, 格式都是不对的, 意思就是一旦又小数或者负数出现就当成不是数字来处理。
我贴一下题干哈
The Government of Nerdvana conducts its elections using an unusual system. Each constituency elects one member to the Nerdvanian Parliament, and each voter casts one ballot in which they can assign any non-negative number of votes to each candidate. Each ballot paper is normalised to a total value of 1 before being counted: for example, given four candidates, the ballot paper

5, 0, 8, 7

would be normalised to
#就是分别每个数来除这几个数的总数
0.25, 0.00, 0.40, 0.35
Any paper that does not fit the above description is declared informal and is disregarded in the count. Example ballot papers and their interpretations are provided.
Once each paper has been normalised, the count operates via a straightforward first-past-the-post system: add up the normalised vote for each candidate, and whoever has the highest total wins the seat.

In this project you will write a Python program that reads in a file of Nerdvanian candidates (example here), and a file of voters' completed ballot papers (example here), and that conducts the counting process for that election (results from the examples here).

然后他给除了下面的9个方程喊我们用。
第一个我会,
第二个你已经告诉我了,我测试了也可以用,但是这个放出2,3,4 是一个组合, call 第四个方程,第2,3个应该工作,我就懵了 , 例子我看得懂但是我确实不晓得咋写。 我问教授,他喊我们自己解决。 真的搞不懂。 然后第5,6个方程也是一个组合, 第6个包含第5个。 我现在的难题就是,我不太会这个方程套用,以前喊我们做作业都是一个一个简单的小方程。
你看了过后可以帮我理下思路嘛,,我弄这个课比我其他课时间多多了, 可能太愚了,确实做不下去。 那个教授说就算过程错了, main函数里面必须包括 getCandidates, getPapers, normalisePapers, countVotes, and printCount. 这5个函数。 不然扣分。

def getCandidates(f):
getCandidates(f) returns a list containing the candidates' names from the file f. The names will be one per line with no extraneous characters. Disregard any blank lines in f. If f doesn't exist, print an appropriate error message and return the empty list.
For example, getCandidates("candidates.txt") = ["Major Clanger", "Soup Dragon", "Froglet", "Iron Chicken", "The Cloud"].

def parseVote(s):
parseVote(s) returns the vote from s. Return 0 for an empty vote, and -1 if there are any non-digits (other than spaces). For example,
parseVote("") = parseVote(" ") = 0,
parseVote("-3") = parseVote("no") = parseVote("1 5") = -1,
parseVote("15") = parseVote(" 15 ") = 15.

def parsePaper(s, n):
parsePaper(s, n) returns the votes from the ballot paper s in an election with n candidates, plus an error message if appropriate. If s is formal, return the list of numbers found in s and the empty string; if s is informal, return an empty list of numbers and the appropriate string below.
For example:
parsePaper("14, , 2", 4) = ([14, 0, 2], ""),
parsePaper(", , ", 4) = parsePaper("0, 0", 4) = ([ ], "blank"),
parsePaper("4, -8, 0", 4) = parsePaper("4, 7.8, 0", 4) = parsePaper("pointless, 5, 5", 4) = ([ ], "non-digits"),
parsePaper("1,2,,4,5", 4) = ([ ], "too long").

parsePaper will use parseVote.

def getPapers(f, n):
getPapers(f, n) returns a list containing the ballot papers from the file f, in an election with n candidates. Treat each line of the file as a separate paper. If f doesn't exist, print an appropriate error message and return the empty list. For example:
getPapers("smallfile.txt", 4) = [([1, 2, 3, 4], ""), ([], "blank"), ([0, 23, 0], ""), ([], "non-digits"), ([], "non-digits"), ([4,0,4,4], ""), ([], "too long"), ([], "blank")].
smallfile.txt is available from the project web-site.

getPapers will use parsePaper.

def normalisePaper(p, n): # sum(p) > 0
normalisePaper(p, n) returns p with each vote scaled according to its total, and padded to contain n votes. For example:
normalisePaper([1,2,3,4], 4) = [0.1, 0.2, 0.3, 0.4], normalisePaper([2], 3) = [1.0, 0.0, 0.0], normalisePaper([0, 4, 496], 3) = [0.000, 0.008, 0.992]

def normalisePapers(ps, n): # for every p on ps, sum(p) > 0
normalisePapers(ps, n) returns ps with each paper normalised, in an election with n candidates.
e.g. normalisePapers([[2], [7, 2, 1]], 3) = [[1.0, 0.0, 0.0], [0.7, 0.2, 0.1]].

normalisePapers will use normalisePaper.

def countVotes(cs, ps): # ps have been normalised for an election with len(cs) candidates
countVotes(cs, ps) returns a list of lists containing the counts for the candidates cs from the ballot papers ps, in descending order of total number of votes. For example, countVotes(["A", "B", "C"], [[0.5, 0.5, 0], [0.05, 0.3, 0.65]]) = [[0.8, "B"], [0.65, "C"], [0.55, "A"]].

def printCount(c):
printCount(c) displays the election count c, i.e. the result from countVotes. See the sample output for the required format.

def main():
main() prompts the user for the names of the necessary files, then conducts the election. See the sample output for the required output.

main will use getCandidates, getPapers, normalisePapers, countVotes, and printCount.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-4-25 18:14:42 | 显示全部楼层
gopythoner 发表于 2017-4-25 17:08
还有这一个我没看懂parsePaper("4, -8, 0", 4) = parsePaper("4, 7.8, 0", 4) = parsePaper("pointless,  ...

你基础比我好多了,我是理解这个老师想让我干啥,可是这东西到我手上了, 我就难以下手。 我觉得这题对我们很超前,,我几个同学都不会,因为我们老师根本没讲具体的任何东西,就讲了一下 def function..就喊我们做这个。。。麻烦你耐心帮帮我呗, 我说加你就是想搞懂这个,我也不想交个答案应付了事。。。麻烦了!!!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-27 21:04:44 From FishC Mobile | 显示全部楼层
2020.3.27考古
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-18 04:28

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表