私信  •  关注

Brian

Brian 最近回复了
3 年前
回复了 Brian 创建的主题 » 第n个修改文件的Git diff?

如果在类似bash的shell中工作,可以定义一个shell函数,例如

function gitdiffn() {
    git diff ${@:2} $(git diff --name-only | sed -n "$1 p") 
}

然后可以用来浏览修改过的文件列表(使用基于1的索引) 像

$ gitdiffn 1
$ gitdiffn 2
# ...

包括 ${@:2} $(command substitution) 在获取第n个文件名时,我们允许向 git diff 调用,所以像

$ gitdiffn 1 --minimal

将按预期工作。

3 年前
回复了 Brian 创建的主题 » 翻译python不能正确地自动检测语言

我做了一个解决方案,解决了我的问题,但没有解决自动检测问题。 在用户输入中添加第二个参数以包含“from_lang”可以解决这个问题。

test = input(">> ")
test = test.split()
to_lang = test[-1].replace("-","")
from_lang = test[-2].replace("-","")
del test[-1]
del test[-1]
test = ' '.join(test)
print(from_lang,to_lang)
print(test)
translator = Translator(from_lang=from_lang, to_lang=to_lang)
translation = translator.translate(test)
print(translation)
5 年前
回复了 Brian 创建的主题 » 如何删除python中的空白

当您将多个参数传递给 print ,默认情况下,在每个值之间插入空格。如果要抑制空格分隔符,请设置 sep 空字符串的关键字参数:

print(
    'Percent males: {:.0f}%' .format(percent_male),
    '\nPercent females: {:.0f}%' .format(percent_female),
    sep='',
)

或者,可以将单个字符串传递给 打印 要完全避免分隔符行为:

print("Percent males: {:.0f}%\nPercent females: {:.0f}%".format(
    percent_male,
    percent_female,
))
16 年前
回复了 Brian 创建的主题 » python:从文件中读取最后的'n'行[重复]

为了提高处理非常大文件的效率(通常在需要使用tail的日志文件情况下),您通常希望避免读取整个文件(即使这样做时不需要立即将整个文件读入内存),但是,您确实需要以某种方式计算行中的偏移量,而不是角色。一种可能是逐字符反向读取seek(),但这非常慢。相反,最好是在更大的块中处理。

我有一个实用功能,我刚才写的文件向后读取,可以在这里使用。

import os, itertools

def rblocks(f, blocksize=4096):
    """Read file as series of blocks from end of file to start.

    The data itself is in normal order, only the order of the blocks is reversed.
    ie. "hello world" -> ["ld","wor", "lo ", "hel"]
    Note that the file must be opened in binary mode.
    """
    if 'b' not in f.mode.lower():
        raise Exception("File must be opened using binary mode.")
    size = os.stat(f.name).st_size
    fullblocks, lastblock = divmod(size, blocksize)

    # The first(end of file) block will be short, since this leaves 
    # the rest aligned on a blocksize boundary.  This may be more 
    # efficient than having the last (first in file) block be short
    f.seek(-lastblock,2)
    yield f.read(lastblock)

    for i in range(fullblocks-1,-1, -1):
        f.seek(i * blocksize)
        yield f.read(blocksize)

def tail(f, nlines):
    buf = ''
    result = []
    for block in rblocks(f):
        buf = block + buf
        lines = buf.splitlines()

        # Return all lines except the first (since may be partial)
        if lines:
            result.extend(lines[1:]) # First line may not be complete
            if(len(result) >= nlines):
                return result[-nlines:]

            buf = lines[0]

    return ([buf]+result)[-nlines:]


f=open('file_to_tail.txt','rb')
for line in tail(f, 20):
    print line

[编辑]添加了更具体的版本(避免了两次反转)