【问题标题】:Reading data in python?在python中读取数据?
【发布时间】:2015-09-27 02:37:28
【问题描述】:

我正在尝试在 Python 中读取数据,我这样做的一种方式是这样

states = """
        Alabama
        Alberta
        Alaska
        Arizona
        Arkansas
        Bob
        Tom
        Ted
        William
        """
states_list = [w.strip().lower() for w in states.splitlines() if w]

现在,如果我试图从文件中读取类似数据,它就无法正常工作。我是这样做的

file1 = open('dictionary_file.txt','r')
data = file1.read()
file1.close()

然后遍历数据中的项目

这里是完整代码,相关部分在最后。

def _get_child_branches(tree):
"""
This method return all the branches of the tree
"""
return tree[1:]


def _get_child_branch(tree, c):
"""
This method returns the specific branch of the tree given the character
"""
for branch in _get_child_branches(tree):
    if branch[0] == c:
        return branch

return None


def _retrive_branch(k, tree):
"""
This method is used for getting the branch for a given word
"""
if not k:
    return None

for c in k:
    child_branch = _get_child_branch(tree, c)
    if not child_branch:
        return None
    tree = child_branch

return tree


def _is_tree_bucket(bucket):
if len(bucket) != 2:
    return False

return type(bucket[1]) is tuple


def _get_bucket_key(bucket):
if not _is_tree_bucket(bucket):
    return None

return bucket[1][0]


def has_key(k, tree):
"""
To check if the tree containes the keyword
"""
return _retrive_branch(k, tree) is not None


def retree_val(k, tree):
key_tuple = _retrive_branch(k, tree)
if not key_tuple:
    return None

return key_tuple[1]


def insert_key(key, v, tree):
"""
Insert a (key, value) pair into tree
"""
if not key or has_key(key, tree):
    return

for char in key:
    branch = _get_child_branch(tree, char)
    if not branch:
        new_branch = [char]
        tree.append(new_branch)
        tree = new_branch
    else:
        tree = branch
tree.append((key, v))


def start_with_prefix(prefix, tree):
"""
Find words start with prefix
"""
branch = _retrive_branch(prefix, tree)
if not branch:
    return []

prefix_list = []
q = branch[1:]
while q:
    curr_branch = q.pop(0)
    if _is_tree_bucket(curr_branch):
        prefix_list.append(_get_bucket_key(curr_branch))
    else:
        q.extend(curr_branch[1:])

return prefix_list






if __name__ == "__main__":
tree = [[]]
file1 = open('dictionary_file.txt','r')
data = file1.read().split('\n')
file1.close()
states = """
        Alabama
        Alberta
        Alaska
        Arizona
        Arkansas
        Bob
        Tom
        Ted
        William"""
states_list = [w.strip().lower() for w in states.splitlines() if w]
print(states_list)
print(states)
for state in data:
    insert_key(state, True, tree)


print start_with_prefix("a", tree)

【问题讨论】:

  • 你的问题是?
  • 三引号不应该只用于文档字符串吗?

标签: python string file io


【解决方案1】:

只需将分割线替换为 file object 并对其进行迭代:

with open('dictionary_file.txt','r') as f:
   lines  =[w.strip().lower() for w in f if w]

除非您确实需要一次数据,否则永远不需要将整个文件读入内存,文件对象是可迭代的,并且会在您迭代时为您提供每一行。

附带说明,您需要在分割线代码中添加if w,因为您在行之前和之后添加换行符,以引号开始字符串并以引号结束,您将不会得到任何空字符串:

states = """Alabama
    Alberta
    Alaska
    Arizona
    Arkansas
    Bob
    Tom
    Ted
    William"""

【讨论】:

  • 我想最后一段是给我的。 :P
  • @Sait,我总是这么说,没什么私人的!很多人一开始总是调用 readlines 或 read 然后将 read 拆分为行列表或迭代 readlines 做他们可以做的工作只是迭代文件对象。
【解决方案2】:

请阅读Reading and writing files

with open('dictionary_file.txt', 'r') as f:
   lines = f.readlines()

states_list = [w.strip().lower() for w in lines if w]

编辑:我意识到这里没有必要使用readlines()。只需使用@Padraic 的答案。

【讨论】:

  • 由于某种原因它不起作用...我的 txt 文件只有一个单词列表,当我将它们放在我的程序中时它可以正常工作,但是如果我尝试使用 file 它会给出错误跨度>
  • @user2939685 它应该可以工作。你得到的错误是什么?但是,我认为您应该选择 Padraic 的答案,它更优雅。
  • 当我打印这两个时,它们是这样打印的,这意味着存在一些问题...['alabama', 'alberta', 'alaska', 'arizona', 'arkansas', ' bob', 'tom', 'ted', 'william'] 阿拉巴马州 艾伯塔 阿拉斯加 亚利桑那 阿肯色州 Bob Tom Ted William
  • 我没有得到什么问题?您能否用预期的输入/输出更新原始问题?
  • 如果我在插入项目的最后一个 for 循环中用 state_list 替换数据,则代码工作。
【解决方案3】:

添加.split('\n') 即可解决。

file1 = open('dictionary_file.txt','r')
data = file1.read().split('\n')
file1.close()
for i in data:
    print i

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 2017-07-12
    • 2012-01-28
    相关资源
    最近更新 更多