Я пытаюсь читать данные в Python один способ, которым я сделать это как этотЧтение данных в 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)
И ваш вопрос? –
Не следует ли использовать тройные кавычки только для docstrings? – Malonge