我有三个输入数据文件.每个都使用不同的分隔符来包含其中的数据.数据文件一个如下所示:
apples | bananas | oranges | grapes
数据文件二看起来像这样:
quarter, dime, nickel, penny
数据文件三看起来像这样:
horse cow pig chicken goat
(列数的变化也是有意的)
我的想法是计算非字母字符的数量,并假设最高计数是分隔符.但是,具有非空格分隔符的文件在分隔符之前和之后也有空格,因此空格会在所有三个文件上获胜.这是我的代码:
def count_chars(s):
valid_seps=[' ','|',',',';','\t']
cnt = {}
for c in s:
if c in valid_seps: cnt[c] = cnt.get(c,0) + 1
return cnt
infile = 'pipe.txt' #or 'comma.txt' or 'space.txt'
records = open(infile,'r').read()
print count_chars(records)Run Code Online (Sandbox Code Playgroud)
它将打印一个字典,其中包含所有可接受字符的计数.在每种情况下,空间总是获胜,所以我不能依靠它来告诉我分隔符是什么.
但我想不出更好的方法来做到这一点.
有什么建议?
我在新工作中一直在教自己Python,并且非常喜欢这门语言.我写了一个简短的类来做一些基本的数据操作,我对此非常有信心.
但是我的结构化/模块化编程时代的旧习惯很难打破,我知道必须有更好的方法来编写它.所以,我想知道是否有人想看看以下内容,并建议一些可能的改进,或者让我找到一个可以帮助我自己发现这些的资源.
快速说明:RandomItems根类是由其他人编写的,我仍然围绕着itertools库.此外,这不是整个模块 - 只是我正在研究的课程,而且它是先决条件.
你怎么看?
import itertools
import urllib2
import random
import string
class RandomItems(object):
"""This is the root class for the randomizer subclasses. These
are used to generate arbitrary content for each of the fields
in a csv file data row. The purpose is to automatically generate
content that can be used as functional testing fixture data.
"""
def __iter__(self):
while True:
yield self.next()
def slice(self, times):
return itertools.islice(self, times)
class RandomWords(RandomItems):
"""Obtain a list of random real …Run Code Online (Sandbox Code Playgroud) 我担心这个问题有点令人费解.我在api上写了一个函数测试,当我查询它时,返回一堆带有嵌入式列表的json.这是一个看起来像的重要片段(所有数据都为此问题匿名):
[{u'account': {u'account_name': u'Autotest Account',
u'account_uid': u'000000000'},
u'address': {u'city': u'AutoTest City',
u'country': u'United States',
u'postal_code': u'10019',
u'province': None,
u'state': u'IL',
u'street': [u'12 Auto Road']},
u'children': [{u'institution_name': u'Autotest Bottom Institution 1',
u'institution_type': 1,
u'institution_uid': u'111111111'},
{u'institution_name': u'Autotest Bottom Institution 2',
u'institution_type': 1,
u'institution_uid': u'222222222'},
{u'institution_name': u'Autotest Bottom Institution 3',
u'institution_type': 1,
u'institution_uid': u'333333333'},
{u'institution_name': u'Autotest Bottom Institution 4',
u'institution_type': 1,
u'institution_uid': u'444444444'},
{u'institution_name': u'Autotest Bottom Institution 5',
u'institution_type': 1,
u'institution_uid': u'555555555'},
{u'institution_name': u'Autotest Bottom Institution 6',
u'institution_type': 1,
u'institution_uid': u'666666666'},
{u'institution_name': …Run Code Online (Sandbox Code Playgroud) python ×3
arrays ×1
csv ×1
dictionary ×1
nested ×1
optimization ×1
parsing ×1
random ×1
string ×1
text-files ×1
textinput ×1