对于列表中的每一行,我试图将其拆分为由" \ t"分隔的三个组件,但是此代码不会被" t"拆分。而是通过信件分割整行。
# Function to load a set of sequences from a given file
# File should be stored as a sequence per line
# Input: File name containing sequences
# Output: List of all sequences in that file
def LoadSeq(FileName):
FileIn = open(FileName, "r")
SeqList = []
for Line in FileIn:
Line = Line.rstrip()
SeqList.append(Line)
FileIn.close()
return SeqList
def LineToList(Str):
Str = Str.rsplit()
return Str.split("\t")
import math
def CalculateDistance(Lat1, Lon1, Lat2, Lon2):
Lat1 = float(Lat1)
Lon1 = float(Lon1)
Lat2 = float(Lat2)
Lon2 = float(Lon2)
nDLat = (Lat1 - Lat2) * 0.017453293
nDLon = (Lon1 - Lon2) * 0.017453293
Lat1 = Lat1 * 0.017453293
Lat2 = Lat2 * 0.017453293
nA = (math.sin(nDLat/2) ** 2) + math.cos(Lat1) * math.cos(Lat2) * (math.sin(nDLon/2) ** 2 )
nC = 2 * math.atan2(math.sqrt(nA),math.sqrt( 1 - nA ))
nD = 6372.797 * nC
return nD
def LocationCount(FileName, DesiredDistance, DesiredLat, DesiredLong):
for Line in LoadSeq(FileName):
LineToList(Line)
Counter = 0
CalculateDistance(Seq[1], Seq[2], DesiredLat, DesiredLong)
if CalculateDistance <= DesiredDistance:
Counter += 1
return Counter
NumberInDistance = LocationCount("Mammal.txt", 20, 50.261667, -5.043333)
print(NumberInDistance)
这是我一直在使用的代码,我没有正确地将它拆分或者我是否正在进一步搞乱它?我必须使用Python,如果可能的话,它必须保持与此类似的forrmatting
答案 0 :(得分:2)
您首先调用rsplit
(未定义特定分隔符)splits the string on any whitespace char。之后,您在列表中调用split
(由rsplit
返回),这将导致异常。
如果您只想按标签拆分,则必须删除LineToList中的第一行。
def LineToList(Str):
return Str.split("\t")
答案 1 :(得分:1)
在您的函数LineToList
中,首先调用.rsplit()
,它将字符串参数转换为列表。然后,您继续调用另一个 .split()
,这会导致错误,因为您只能在字符串上调用.split()
。
相反,请将您的功能更改为:
def LineToList(Str):
return Str.replace("\t", " ").rsplit()
将'\t'
更改为' '
,从而使其能够通过.rsplit()
进行识别。
>>> def LineToList(Str):
... return Str.replace("\t", " ").rsplit()
...
>>> LineToList("hi\tthis\tis\tdata")
['hi', 'this', 'is', 'data']
>>>