【问题标题】:How to split a file which is delimited by bullet points如何拆分由项目符号分隔的文件
【发布时间】:2015-07-29 23:50:39
【问题描述】:

我正在尝试拆分一个包含多个段落的大文件,每个段落的长度都是可变的,唯一的分隔符将是下一段的要点...

有没有办法为每个单独的段落获取几个不同的文件? 最后一件事是将每个单独的段落写入 MySQL DB...

示例输入:

  • Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。 Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat。

  • Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur。 Exceptioneur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum。”

输出:每个段落都是数据库中的一个单独条目

【问题讨论】:

  • 你能提供示例输入和输出文件吗?
  • 按要点你想说什么。你可以使用 .split("你要在此处分隔的字符")
  • 这不是纯文本?
  • 这是纯文本吗
  • 你有只有一列的数据库

标签: python mysql bash


【解决方案1】:

这是您按项目符号拆分文件的方式:

new_files = open(source_file).read().split(u'\u2022')
for par in new_files:
  open("%s.txt"%new_files.index(par),"w").write("%s"%par) 
  LOAD DATA INFILE "%s.txt"%new_files.index(par) INTO TABLE your_DB_name.your_table; 

【讨论】:

  • 完美!以及如何将输出作为单独的条目注入 MySQL 数据库
  • 您要将新文件插入为 .txt 还是将段落插入为字符串?
  • 段落作为字符串,有一个小错误“ Unicode decode error: ascii codec can not decode byte.... ordinal not in range (128)
  • 对不起,我的意思是尝试以这种方式添加 encode('utf-8') open("%s.txt"%new_files.index(par),"w").write("%s"%par.encode('utf-8')))
  • @Did 感谢您接受答案,如果这对您有帮助
【解决方案2】:

这会连接到 mysql DB 并读取文件并在每个项目符号处将其拆分并将数据插入到 mysql DB 表中

我的代码:

#Server Connection to MySQL:

import MySQLdb
conn = MySQLdb.connect(host= "localhost",
              user="root",
              passwd="newpassword",
              db="db")
x = conn.cursor()

try:
    file_data = open("FILE_NAME_WITH_EXTENSION").read().split(u'\u2022')
    for text in file_data:
        print text
        x.execute("""INSERT INTO TABLE_NAME VALUES (%s)""",(text))
        conn.commit()
except:
    conn.rollback()

conn.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 2012-05-24
    • 1970-01-01
    • 2012-09-17
    相关资源
    最近更新 更多